Given a binary tree, print all nodes between two given levels in a binary tree. Print the nodes level wise, i.e., the nodes for any level should be printed from left to right.
In the above tree, if the starting level is 2 and the ending level is 3 then the solution should print:
2 3 4 5 6 7
Note: Level number starts with 1. That is, the root node is at level 1.
Prerequisite: Level order Traversal.
The idea is to do level order traversal of the tree using a queue and keep track of the current level. If the current level lies between the starting and ending level then print the nodes at that level.
levelordertraverse (root, startLevel, endLevel) q -> empty queue q.enqueue (root) level -> 0 while (not q.isEmpty()) size -> q.size() level = level + 1 while (size) node -> q.dequeue() if (level between startLevel and endevel) print (node) if(node.leftnull) q.enqueue (node. left) if(node.leftnull) q.enqueue(node.right) size =size -1
Below is the implementation of the above algorithm:
2 3 4 5 6 7
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Print Levels of all nodes in a Binary Tree
- Print alternate nodes from all levels of a Binary 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 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
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Print levels with odd number of nodes and even number of nodes
- Print all Palindromic Levels Of a Binary Tree
- Print all K-sum levels in a Binary Tree
- Print all Prime Levels of a Binary Tree
- Print all Co-Prime Levels of a Binary Tree
- Print all Exponential Levels of a Binary Tree
- Print the nodes at odd levels of a tree
- Print all the levels with odd and even number of nodes in it | Set-2
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print Binary Tree levels in sorted order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.