VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-nodes-between-two-given-levels-in-binary-tree/

⇱ All nodes between two given levels in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All nodes between two given levels in Binary Tree

Last Updated : 11 Jul, 2025

Given a binary tree, the task is to 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. 

Note: The levels are 1-indexed, i.e., root node is at level 1.

Example:

Input: Binary tree, l = 2, h = 3

👁 Image

Output:
2 3
4 5 6 7

Using Recursion - O(n) time and O(n) space

The idea is to perform a preorder traversal of the binary tree while keeping track of the current level.

Step by step approach:

  1. Maintain a result array of arrays to store nodes at each level.
  2. Traverse the tree recursively using preorder traversal (root, left, right).
  3. Track the current level during traversal.
  4. If current level is between low and high boundaries, add node to appropriate level in result.
  5. If needed, create a new vector for a level not yet encountered.

Output
2 3 
4 5 6 7 

Using Level Order Traversal - O(n) time and O(n) space

Refer to Print nodes between two given levels - Level Order for detailed explanation and approach.


Comment