![]() |
VOOZH | about |
Given a binary tree and two level numbers 'low' and 'high', print nodes from level low to level high.
For example consider the binary tree given in below diagram. Input: Root of below tree, low = 2, high = 4 Output: 8 22 4 12 10 14
A Simple Method is to first write a recursive function that prints nodes of a given level number. Then call a recursive function in a loop from low to high. Time complexity of this method is O(n2)
We can print nodes in O(n) time using queue-based iterative level order traversal. The idea is to do simple queue-based level order traversal. While doing inorder traversal, add a marker node at the end. Whenever we see a marker node, we increase level number. If level number is between low and high, then print nodes.
The following is the implementation of above idea.
Implementation:
Level Order traversal between given two levels is 8 22 4 12
Time complexity of above method is O(n) as it does a simple level order traversal.
Auxiliary Space: O(N) where N is the number of nodes in the binary tree due to queue.