Open In App

All nodes between two given levels in Binary Tree

Last Updated : 11 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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.
C++
// C++ program to Print all nodes between
// two given levels in Binary Tree
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

void preOrder(Node* root, int level, int l, 
int h, vector<vector<int>>& res) {
    if (root == nullptr)
        return;
    
    // If current level is within range, add to result
    if (level >= l && level <= h) {
        
        // Adjust index as our result array is 0-indexed
        int idx = level - l;
        
        // Make sure we have an array for this level
        if (idx >= res.size()) {
            res.push_back(vector<int>());
        }
        
        // Add current node's data to appropriate level
        res[idx].push_back(root->data);
    }
    
    // Traverse left and right subtrees
    preOrder(root->left, level + 1, l, h, res);
    preOrder(root->right, level + 1, l, h, res);
}

vector<vector<int>> printLevels(Node* root, int l, int h) {
    vector<vector<int>> res;
    preOrder(root, 1, l, h, res);
    return res;
}

int main() {
    
    //             1
    //          /     \
    //        2         3
    //      /   \     /   \
    //     4     5   6     7
    //    / \   / \ / \   / \
    //   8  9 10 11 12 13 14 15
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);
    root->left->left->left = new Node(8);
    root->left->left->right = new Node(9);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(11);
    root->right->left->left = new Node(12);
    root->right->left->right = new Node(13);
    root->right->right->left = new Node(14);
    root->right->right->right = new Node(15);
    
    int l = 2, h = 3;
    
    vector<vector<int>> res = printLevels(root, l, h);
    for (auto v: res) {
        for (auto node: v) cout << node << " ";
        cout << endl;
    }
    return 0;
}
Java
// Java program to Print all nodes between
// two given levels in Binary Tree

import java.util.ArrayList;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // If current level is within range, add to result
    static void preOrder(Node root, int level, int l, 
    int h, ArrayList<ArrayList<Integer>> res) {
        if (root == null)
            return;

        if (level >= l && level <= h) {

            // Adjust index as our result array is 0-indexed
            int idx = level - l;

            // Make sure we have an array for this level
            if (idx >= res.size()) {
                res.add(new ArrayList<>());
            }

            // Add current node's data to appropriate level
            res.get(idx).add(root.data);
        }

        // Traverse left and right subtrees
        preOrder(root.left, level + 1, l, h, res);
        preOrder(root.right, level + 1, l, h, res);
    }

    static ArrayList<ArrayList<Integer>> printLevels(Node root, int l, int h) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        preOrder(root, 1, l, h, res);
        return res;
    }

    public static void main(String[] args) {

        //             1
        //          /     \
        //        2         3
        //      /   \     /   \
        //     4     5   6     7
        //    / \   / \ / \   / \
        //   8  9 10 11 12 13 14 15
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.left.left = new Node(8);
        root.left.left.right = new Node(9);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(11);
        root.right.left.left = new Node(12);
        root.right.left.right = new Node(13);
        root.right.right.left = new Node(14);
        root.right.right.right = new Node(15);

        int l = 2, h = 3;

        ArrayList<ArrayList<Integer>> res = printLevels(root, l, h);
        for (ArrayList<Integer> v : res) {
            for (int node : v) System.out.print(node + " ");
            System.out.println();
        }
    }
}
Python
# Python program to Print all nodes between
# two given levels in Binary Tree

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# If current level is within range, add to result
def preOrder(root, level, l, h, res):
    if root is None:
        return

    if level >= l and level <= h:

        # Adjust index as our result array is 0-indexed
        idx = level - l

        # Make sure we have an array for this level
        if idx >= len(res):
            res.append([])

        # Add current node's data to appropriate level
        res[idx].append(root.data)

    # Traverse left and right subtrees
    preOrder(root.left, level + 1, l, h, res)
    preOrder(root.right, level + 1, l, h, res)

def printLevels(root, l, h):
    res = []
    preOrder(root, 1, l, h, res)
    return res

if __name__ == "__main__":

    #             1
    #          /     \
    #        2         3
    #      /   \     /   \
    #     4     5   6     7
    #    / \   / \ / \   / \
    #   8  9 10 11 12 13 14 15
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)
    root.left.left.left = Node(8)
    root.left.left.right = Node(9)
    root.left.right.left = Node(10)
    root.left.right.right = Node(11)
    root.right.left.left = Node(12)
    root.right.left.right = Node(13)
    root.right.right.left = Node(14)
    root.right.right.right = Node(15)

    l, h = 2, 3

    res = printLevels(root, l, h)
    for v in res:
        for node in v:
            print(node, end=" ")
        print()
C#
// C# program to Print all nodes between
// two given levels in Binary Tree

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // If current level is within range, add to result
    static void preOrder(Node root, int level, 
    int l, int h, List<List<int>> res) {
        if (root == null)
            return;

        if (level >= l && level <= h) {

            // Adjust index as our result array is 0-indexed
            int idx = level - l;

            // Make sure we have an array for this level
            if (idx >= res.Count) {
                res.Add(new List<int>());
            }

            // Add current node's data to appropriate level
            res[idx].Add(root.data);
        }

        // Traverse left and right subtrees
        preOrder(root.left, level + 1, l, h, res);
        preOrder(root.right, level + 1, l, h, res);
    }

    static List<List<int>> printLevels(Node root, int l, int h) {
        List<List<int>> res = new List<List<int>>();
        preOrder(root, 1, l, h, res);
        return res;
    }

    static void Main(string[] args) {

        //             1
        //          /     \
        //        2         3
        //      /   \     /   \
        //     4     5   6     7
        //    / \   / \ / \   / \
        //   8  9 10 11 12 13 14 15
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.left.left = new Node(8);
        root.left.left.right = new Node(9);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(11);
        root.right.left.left = new Node(12);
        root.right.left.right = new Node(13);
        root.right.right.left = new Node(14);
        root.right.right.right = new Node(15);

        int l = 2, h = 3;

        List<List<int>> res = printLevels(root, l, h);
        foreach (var v in res) {
            foreach (var node in v)
                Console.Write(node + " ");
            Console.WriteLine();
        }
    }
}
JavaScript
// JavaScript program to Print all nodes between
// two given levels in Binary Tree

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// If current level is within range, add to result
function preOrder(root, level, l, h, res) {
    if (root === null)
        return;

    if (level >= l && level <= h) {

        // Adjust index as our result array is 0-indexed
        let idx = level - l;

        // Make sure we have an array for this level
        if (idx >= res.length) {
            res.push([]);
        }

        // Add current node's data to appropriate level
        res[idx].push(root.data);
    }

    // Traverse left and right subtrees
    preOrder(root.left, level + 1, l, h, res);
    preOrder(root.right, level + 1, l, h, res);
}

function printLevels(root, l, h) {
    let res = [];
    preOrder(root, 1, l, h, res);
    return res;
}

//             1
//          /     \
//        2         3
//      /   \     /   \
//     4     5   6     7
//    / \   / \ / \   / \
//   8  9 10 11 12 13 14 15
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.left.left.left = new Node(8);
root.left.left.right = new Node(9);
root.left.right.left = new Node(10);
root.left.right.right = new Node(11);
root.right.left.left = new Node(12);
root.right.left.right = new Node(13);
root.right.right.left = new Node(14);
root.right.right.right = new Node(15);

let l = 2, h = 3;

let res = printLevels(root, l, h);
for (let v of res) {
    console.log(v.join(" "));
}

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.




Next Article

Similar Reads