VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-binary-tree-print-nodes-two-given-level-numbers/

⇱ Print nodes between two given level numbers of a binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print nodes between two given level numbers of a binary tree

Last Updated : 12 Jan, 2023

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

👁 BST_LCA

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:


Output
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.

Comment
Article Tags: