Open In App

Print all nodes between two given levels in Binary Tree

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Algorithm: 

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: 

C++




// C++ program for Print all nodes
// between two given levels in
// a binary Node
#include<bits/stdc++.h>
using namespace std;
  
// Class containing left and right
// child of current node and key value
struct Node{
    int data;
    Node *left, *right;
};
 
Node* newNode(int x){
    Node* temp = new Node();
    temp->data = x;
    temp->left = temp->right = NULL;
    return temp;
}
  
// Iterative function to print all
// nodes between two given
// levels in a binary Node
void printNodes(Node* root, int start, int end){
    if (root == NULL) return;
  
    // create an empty queue and
    // enqueue root node
    queue<Node*> queue;
    queue.push(root);
  
    // pointer to store current node
    Node *curr = NULL;
  
    // maintains level of current node
    int level = 0;
  
    // run till queue is not empty
    while (!queue.empty()) {
        // increment level by 1
        level++;
        // calculate number of nodes in
        // current level
        int size = queue.size();
        // process every node of current level
        // and enqueue their non-empty left
        // and right child to queue
        while (size != 0){
            curr = queue.front();
            queue.pop();
  
            // print the node if its level is
            // between given levels
            if (level >= start && level <= end) cout<<curr->data<<" ";
            if (curr->left != NULL) queue.push(curr->left);
  
            if (curr->right != NULL) queue.push(curr->right);
            size--;
        }
  
        if (level >= start && level <= end) cout<<"\n";
    }
}
  
// Driver Code
int main(){
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
  
    /* Constructed binary Node is
         1
        / \
       2   3
      / \ / \
      4 5 6 7 */
  
    int start = 2, end = 3;
    printNodes(root, start, end);
}
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL


Java




// Java program for Print all nodes
// between two given levels in
// a binary tree
 
import java.util.LinkedList;
import java.util.Queue;
 
public class BinaryTree {
 
    // Class containing left and right
    // child of current node and key value
    static class Node {
 
        int data;
        Node left, right;
 
        public Node(int item)
        {
            data = item;
            left = right = null;
        }
    }
 
    // Root of the Binary Tree
    Node root;
    public BinaryTree()
    {
        root = null;
    }
 
    // Iterative function to print all
    // nodes between two given
    // levels in a binary tree
    void printNodes(Node root, int start, int end)
    {
        if (root == null) {
            return;
        }
 
        // create an empty queue and
        // enqueue root node
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
 
        // pointer to store current node
        Node curr = null;
 
        // maintains level of current node
        int level = 0;
 
        // run till queue is not empty
        while (!queue.isEmpty()) {
            // increment level by 1
            level++;
 
            // calculate number of nodes in
            // current level
            int size = queue.size();
 
            // process every node of current level
            // and enqueue their non-empty left
            // and right child to queue
            while (size != 0) {
                curr = queue.poll();
 
                // print the node if its level is
                // between given levels
                if (level >= start && level <= end) {
                    System.out.print(curr.data + " ");
                }
                if (curr.left != null) {
                    queue.add(curr.left);
                }
 
                if (curr.right != null) {
                    queue.add(curr.right);
                }
                size--;
            }
 
            if (level >= start && level <= end) {
                System.out.println("");
            };
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
 
        /* Constructed binary tree is
             1
           /  \
          2    3
         / \  / \
        4   5 6  7 */
 
        int start = 2, end = 3;
 
        tree.printNodes(tree.root, start, end);
    }
}


Python3




# Python3 program for Print all nodes
# between two given levels in
# a binary tree
 
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.                                
class newNode:
 
    # Construct to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# Iterative function to print all
# nodes between two given
# levels in a binary tree
def printNodes(root, start, end):
     
    if (root == None):
        return
 
    # create an empty queue and
    # enqueue root node
    q = []
    q.append(root)
 
    # pointer to store current node
    curr = None
 
    # maintains level of current node
    level = 0
 
    # run till queue is not empty
    while (len(q)):
         
        # increment level by 1
        level += 1
 
        # calculate number of nodes in
        # current level
        size = len(q)
 
        # process every node of current level
        # and enqueue their non-empty left
        # and right child to queue
        while (size != 0) :
            curr = q[0]
            q.pop(0)
 
            # print the node if its level is
            # between given levels
            if (level >= start and level <= end) :
                print(curr.data, end = " ")
             
            if (curr.left != None) :
                q.append(curr.left)
             
            if (curr.right != None) :
                q.append(curr.right)
             
            size -= 1
         
        if (level >= start and level <= end) :
            print("")
             
# Driver Code
if __name__ == '__main__':
     
    """
    Let us create Binary Tree shown
    in above example """
    root = newNode(1)
    root.left = newNode(2)
 
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.right = newNode(3)
    root.right.right = newNode(7)
    root.right.left = newNode(6)
    start = 2
    end = 3
    printNodes(root, start, end)
     
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program for Print all nodes
// between two given levels in
// a binary tree
using System;
using System.Collections.Generic;
 
public class BinaryTree
{
 
    // Class containing left and right
    // child of current node and key value
    public class Node
    {
 
        public int data;
        public Node left, right;
 
        public Node(int item)
        {
            data = item;
            left = right = null;
        }
    }
 
    // Root of the Binary Tree
    Node root;
 
    public BinaryTree()
    {
        root = null;
    }
 
    // Iterative function to print all
    // nodes between two given
    // levels in a binary tree
    void printNodes(Node root, int start, int end)
    {
        if (root == null)
        {
            return;
        }
 
        // create an empty queue and
        // enqueue root node
        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);
 
        // pointer to store current node
        Node curr = null;
 
        // maintains level of current node
        int level = 0;
 
        // run till queue is not empty
        while (queue.Count >0)
        {
            // increment level by 1
            level++;
 
            // calculate number of nodes in
            // current level
            int size = queue.Count;
 
            // process every node of current level
            // and enqueue their non-empty left
            // and right child to queue
            while (size != 0)
            {
                curr = queue.Peek();
                queue.Dequeue();
 
                // print the node if its level is
                // between given levels
                if (level >= start && level <= end)
                {
                    Console.Write(curr.data + " ");
                }
                if (curr.left != null)
                {
                    queue.Enqueue(curr.left);
                }
 
                if (curr.right != null)
                {
                    queue.Enqueue(curr.right);
                }
                size--;
            }
 
            if (level >= start && level <= end)
            {
                Console.WriteLine("");
            };
        }
    }
 
    // Driver Code
    public static void Main(String []args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
 
        /* Constructed binary tree is
            1
        / \
        2 3
        / \ / \
        4 5 6 7 */
        int start = 2, end = 3;
 
        tree.printNodes(tree.root, start, end);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
    // Javascript program for Print all nodes
    // between two given levels in
    // a binary tree
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    // Root of the Binary Tree
    let root = null;
  
    // Iterative function to print all
    // nodes between two given
    // levels in a binary tree
    function printNodes(root, start, end)
    {
        if (root == null) {
            return;
        }
  
        // create an empty queue and
        // enqueue root node
        let queue = [];
        queue.push(root);
  
        // pointer to store current node
        let curr = null;
  
        // maintains level of current node
        let level = 0;
  
        // run till queue is not empty
        while (queue.length > 0) {
            // increment level by 1
            level++;
  
            // calculate number of nodes in
            // current level
            let size = queue.length;
  
            // process every node of current level
            // and enqueue their non-empty left
            // and right child to queue
            while (size != 0) {
                curr = queue[0];
                queue.shift();
  
                // print the node if its level is
                // between given levels
                if (level >= start && level <= end) {
                    document.write(curr.data + " ");
                }
                if (curr.left != null) {
                    queue.push(curr.left);
                }
  
                if (curr.right != null) {
                    queue.push(curr.right);
                }
                size--;
            }
  
            if (level >= start && level <= end) {
                document.write("</br>");
            }
        }
    }
     
    let tree = new Node(0);
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
    tree.root.right.left = new Node(6);
    tree.root.right.right = new Node(7);
 
    /* Constructed binary tree is
               1
             /  \
            2    3
           / \  / \
          4   5 6  7 */
 
    let start = 2, end = 3;
 
    printNodes(tree.root, start, end);
  
 // This code is contributed by decode2207.
</script>


Output

2 3 
4 5 6 7 

Time Complexity: O(n)

As we traverse the tree just once.

Auxiliary space: O(b)

Here b is the breadth of the tree. The extra space is used to store the elements of the current level in the queue.

Recursive Approach(Method-2):
Follow the below steps to solve this problem:
1) Create an vector of vector to store the ans in level order fashion.
2) Recursively traverse the whole tree in inorder fashion and keep track the level along with each node.
3) If the level of node lie between the given levels then store them in ans vector respectively to its level number.
4) After traversing the whole tree print the ans vector.

Below is the implementation of above approach:

C++




// C++ program to print all nodes between
// two given levels
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
struct Node{
    int data;
    struct Node* left;
    struct Node* right;
};
 
// utility function to initialize the new node
Node* newNode(int data){
    Node *new_node = new Node();
    new_node->data = data;
    new_node->left = NULL;
    new_node->right = NULL;
    return new_node;
}
 
// Recursive function to print all nodes between two given
// levels in a binary tree
void printNodes(Node* root, int start, int end, vector<vector<int>> &ans, int level){
    if(root == NULL) return;
    printNodes(root->left, start, end, ans, level+1);
    if(level >= start && level <= end){
        ans[level-start].push_back(root->data);
    }
    printNodes(root->right, start, end, ans, level+1);
}
 
 
// driver code to test above function
int main(){
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
 
    int start = 2;
    int end = 3;
    // function call
    vector<vector<int>> ans(end-start+1);
    printNodes(root, start, end, ans, 1);
    for(auto i : ans){
        for(int j : i){
            cout<<j<<" ";
        }
        cout<<endl;
    }
    return 0;
}
 
// THIS CODE IS CONTRIBUTED BY KIRIT AGARWAL(KIRTIAGARWAL23121999)


Java




// Java program to print all nodes between
// two given levels in a binary tree
import java.util.*;
 
// A binary tree node
class Node {
    int data;
    Node left, right;
 
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
    Node root;
 
    // utility function to initialize the new node
    Node newNode(int data) {
        Node new_node = new Node(data);
        new_node.left = null;
        new_node.right = null;
        return new_node;
    }
 
    // Recursive function to print all nodes between two given
    // levels in a binary tree
    void printNodes(Node root, int start, int end, List<List<Integer>> ans, int level) {
        if (root == null) {
            return;
        }
        printNodes(root.left, start, end, ans, level + 1);
        if (level >= start && level <= end) {
            ans.get(level - start).add(root.data);
        }
        printNodes(root.right, start, end, ans, level + 1);
    }
 
    // driver code to test above function
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = tree.newNode(1);
        tree.root.left = tree.newNode(2);
        tree.root.right = tree.newNode(3);
        tree.root.left.left = tree.newNode(4);
        tree.root.left.right = tree.newNode(5);
        tree.root.right.left = tree.newNode(6);
        tree.root.right.right = tree.newNode(7);
 
        int start = 2;
        int end = 3;
        List<List<Integer>> ans = new ArrayList<>(end - start + 1);
        for (int i = 0; i < end - start + 1; i++) {
            ans.add(i, new ArrayList<Integer>());
        }
        // function call
        tree.printNodes(tree.root, start, end, ans, 1);
        for (List<Integer> i : ans) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}


Python3




# Python program to print all nodes between
# two given levels
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
  
     
# utility function to get the new node
def newNode(data):
    return Node(data)
 
 
# Recursive function to print all nodes between two given
# levels in a binary tree
def printNodes(root, start, end, ans, level):
    if(root is None):
        return
    printNodes(root.left, start, end, ans, level+1)
    if(level >= start and level <= end):
        ans[level-start].append(root.data)
    printNodes(root.right, start, end, ans, level+1)
     
 
# driver code to test above function
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
 
start = 2
end = 3
ans = []
for i in range(end-start+1):
    temp = []
    ans.append(temp)
 
# function call
printNodes(root, start, end, ans, 1)
for i in range(len(ans)):
    for j in range (len(ans[i])):
        print(ans[i][j], end=" ")
    print("")


C#




// C# program to print all nodes between two given levels in
// a binary tree
 
using System;
using System.Collections.Generic;
 
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class GFG {
 
    public Node root;
 
    // Utility function to initialize the new node
    public Node NewNode(int data)
    {
        Node newNode = new Node(data);
        newNode.left = null;
        newNode.right = null;
        return newNode;
    }
 
    // Recursive function to print all nodes between two
    // given levels in a binary tree
    public void PrintNodes(Node root, int start, int end,
                           List<List<int> > ans, int level)
    {
        if (root == null) {
            return;
        }
        PrintNodes(root.left, start, end, ans, level + 1);
        if (level >= start && level <= end) {
            ans[level - start].Add(root.data);
        }
        PrintNodes(root.right, start, end, ans, level + 1);
    }
 
    static public void Main()
    {
 
        // Code
        GFG tree = new GFG();
        tree.root = tree.NewNode(1);
        tree.root.left = tree.NewNode(2);
        tree.root.right = tree.NewNode(3);
        tree.root.left.left = tree.NewNode(4);
        tree.root.left.right = tree.NewNode(5);
        tree.root.right.left = tree.NewNode(6);
        tree.root.right.right = tree.NewNode(7);
 
        int start = 2;
        int end = 3;
        List<List<int> > ans
            = new List<List<int> >(end - start + 1);
        for (int i = 0; i < end - start + 1; i++) {
            ans.Add(new List<int>());
        }
        // Function call
        tree.PrintNodes(tree.root, start, end, ans, 1);
        for (int i = 0; i < ans.Count; i++) {
            for (int j = 0; j < ans[i].Count; j++) {
                Console.Write(ans[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
 
// This code is contributed by lokesh.


Javascript




// JavaScript Program to print all nodes between
// two given levels
// a binary tree node
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// utility function to initialize the new node
function newNode(data){
    return new Node(data);
}
 
// Recursive function to print all nodes between two given
// levels in a binary tree
function printNodes(root, start, end, ans, level){
    if(root == null) return;
    printNodes(root.left, start, end, ans, level+1);
    if(level >= start && level <= end){
        ans[level-start].push(root.data);
    }
    printNodes(root.right, start, end, ans, level+1);
}
  
  
// driver code to test above function
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
 
let start = 2;
let end = 3;
let ans = [];
for(let i = 0; i<end-start+1; i++){
    ans[i] = [];
}
 
// function call
printNodes(root, start, end,ans, 1);
for(let i = 0; i < ans.length; i++)
{
    for(let j = 0; j < ans[i].length; j++)
    {
        console.log(ans[i][j] + " ");
    }
    console.log("<br>");
}
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002 )


Output

2 3 
4 5 6 7 

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space : O(N) where N is the number of nodes.



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads