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 starting level is 2 and ending level is 3 then 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
- Print Levels of all nodes in a Binary Tree
- Print odd positioned nodes of even 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 odd levels in level order of the given binary tree
- Print the nodes at odd levels of a tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print Nodes in Top View of Binary Tree
- Print all even nodes of Binary Search Tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.