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 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.
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.
This article is contributed by Frank. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Print the nodes corresponding to the level value for each level of a Binary Tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Difference between sums of odd level and even level nodes in an N-ary Tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print extreme nodes of each level of Binary Tree in alternate order
- Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
- Print all nodes except rightmost node of every level of the Binary Tree
- Print the middle nodes of each level of a Binary Tree
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Count nodes with two children at level L in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Connect Nodes at same Level (Level Order Traversal)
- Check if max sum level of Binary tree divides tree into two equal sum halves