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

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:
C++
// A C++ program to print Nodes level by level between given two levels.
#include <bits/stdc++.h>
using namespace std;
/* A binary tree Node has key, pointer to left and right children */
struct Node
{
int key;
struct Node* left, *right;
};
/* Given a binary tree, print nodes from level number 'low' to level
number 'high'*/
void printLevels(Node* root, int low, int high)
{
queue <Node *> Q;
Node *marker = new Node; // Marker node to indicate end of level
int level = 1; // Initialize level number
// Enqueue the only first level node and marker node for end of level
Q.push(root);
Q.push(marker);
// Simple level order traversal loop
while (Q.empty() == false)
{
// Remove the front item from queue
Node *n = Q.front();
Q.pop();
// Check if end of level is reached
if (n == marker)
{
// print a new line and increment level number
cout << endl;
level++;
// Check if marker node was last node in queue or
// level number is beyond the given upper limit
if (Q.empty() == true || level > high) break;
// Enqueue the marker for end of next level
Q.push(marker);
// If this is marker, then we don't need print it
// and enqueue its children
continue;
}
// If level is equal to or greater than given lower level,
// print it
if (level >= low)
cout << n->key << " ";
// Enqueue children of non-marker node
if (n->left != NULL) Q.push(n->left);
if (n->right != NULL) Q.push(n->right);
}
}
/* Helper function that allocates a new Node with the
given key and NULL left and right pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/* Driver program to test above functions*/
int main()
{
// Let us construct the BST shown in the above figure
struct Node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
cout << "Level Order traversal between given two levels is";
printLevels(root, 2, 3);
return 0;
}
Java
// Java program to print Nodes level by level between given two levels
import java.util.LinkedList;
import java.util.Queue;
/* A binary tree Node has key, pointer to left and right children */
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Given a binary tree, print nodes from level number 'low' to level
number 'high'*/
void printLevels(Node node, int low, int high)
{
Queue<Node> Q = new LinkedList<>();
Node marker = new Node(4); // Marker node to indicate end of level
int level = 1; // Initialize level number
// Enqueue the only first level node and marker node for end of level
Q.add(node);
Q.add(marker);
// Simple level order traversal loop
while (Q.isEmpty() == false)
{
// Remove the front item from queue
Node n = Q.peek();
Q.remove();
// Check if end of level is reached
if (n == marker)
{
// print a new line and increment level number
System.out.println("");
level++;
// Check if marker node was last node in queue or
// level number is beyond the given upper limit
if (Q.isEmpty() == true || level > high)
break;
// Enqueue the marker for end of next level
Q.add(marker);
// If this is marker, then we don't need print it
// and enqueue its children
continue;
}
// If level is equal to or greater than given lower level,
// print it
if (level >= low)
System.out.print( n.data + " ");
// Enqueue children of non-marker node
if (n.left != null)
Q.add(n.left);
if (n.right != null)
Q.add(n.right);
}
}
// Driver program to test for above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
System.out.print("Level Order traversal between given two levels is ");
tree.printLevels(tree.root, 2, 3);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python program to print nodes level by level between
# given two levels
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Given a binary tree, print nodes form level number 'low'
# to level number 'high'
def printLevels(root, low, high):
Q = []
marker = Node(11114) # Marker node to indicate end of level
level = 1 # Initialize level number
# Enqueue the only first level node and marker node for
# end of level
Q.append(root)
Q.append(marker)
#print Q
# Simple level order traversal loop
while(len(Q) >0):
# Remove the front item from queue
n = Q[0]
Q.pop(0)
#print Q
# Check if end of level is reached
if n == marker:
# print a new line and increment level number
print()
level += 1
# Check if marker node was last node in queue
# or level number is beyond the given upper limit
if len(Q) == 0 or level > high:
break
# Enqueue the marker for end of next level
Q.append(marker)
# If this is marker, then we don't need print it
# and enqueue its children
continue
if level >= low:
print (n.key,end=" ")
# Enqueue children of non-marker node
if n.left is not None:
Q.append(n.left)
Q.append(n.right)
# Driver program to test the above function
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
print ("Level Order Traversal between given two levels is",printLevels(root,2,3))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
using System;
using System.Collections.Generic;
// c# program to print Nodes level by level between given two levels
/* A binary tree Node has key, pointer to left and right children */
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
public Node root;
/* Given a binary tree, print nodes from level number 'low' to level
number 'high'*/
public virtual void printLevels(Node node, int low, int high)
{
LinkedList<Node> Q = new LinkedList<Node>();
Node marker = new Node(4); // Marker node to indicate end of level
int level = 1; // Initialize level number
// Enqueue the only first level node and marker node for end of level
Q.AddLast(node);
Q.AddLast(marker);
// Simple level order traversal loop
while (Q.Count > 0)
{
// Remove the front item from queue
Node n = Q.First.Value;
Q.RemoveFirst();
// Check if end of level is reached
if (n == marker)
{
// print a new line and increment level number
Console.WriteLine("");
level++;
// Check if marker node was last node in queue or
// level number is beyond the given upper limit
if (Q.Count == 0 || level > high)
{
break;
}
// Enqueue the marker for end of next level
Q.AddLast(marker);
// If this is marker, then we don't need print it
// and enqueue its children
continue;
}
// If level is equal to or greater than given lower level,
// print it
if (level >= low)
{
Console.Write(n.data + " ");
}
// Enqueue children of non-marker node
if (n.left != null)
{
Q.AddLast(n.left);
}
if (n.right != null)
{
Q.AddLast(n.right);
}
}
}
// Driver program to test for above functions
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
Console.Write("Level Order traversal between given two levels is ");
tree.printLevels(tree.root, 2, 3);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// JavaScript program to print Nodes
// level by level between given two levels
/* A binary tree Node has key, pointer to
left and right children */
class Node
{
constructor(item)
{
this.data = item;
this.left = null;
this.right = null;
}
}
var root = null;
/* Given a binary tree, print nodes
from level number 'low' to level
number 'high'*/
function printLevels(node, low, high)
{
var Q = [];
var marker = new Node(4); // Marker node to indicate end of level
var level = 1; // Initialize level number
// Enqueue the only first level node and
// marker node for end of level
Q.push(node);
Q.push(marker);
// Simple level order traversal loop
while (Q.length > 0)
{
// Remove the front item from queue
var n = Q[0];
Q.shift();
// Check if end of level is reached
if (n == marker)
{
// print a new line and increment level number
document.write("<br>");
level++;
// Check if marker node was last node in queue or
// level number is beyond the given upper limit
if (Q.length == 0 || level > high)
{
break;
}
// Enqueue the marker for end of next level
Q.push(marker);
// If this is marker, then we don't need print it
// and enqueue its children
continue;
}
// If level is equal to or greater than given lower level,
// print it
if (level >= low)
{
document.write(n.data + " ");
}
// Enqueue children of non-marker node
if (n.left != null)
{
Q.push(n.left);
}
if (n.right != null)
{
Q.push(n.right);
}
}
}
// Driver program to test for above functions
root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
document.write("Level Order traversal between given two levels is ");
printLevels(root, 2, 3);
</script>
OutputLevel 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.
Print nodes between two given level numbers of a binary tree
Similar Reads
Print all nodes between two given levels in Binary Tree 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 = 3Output
8 min read
Print Levels of all nodes in a Binary Tree Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
7 min read
Print all Nodes of given Binary Tree at the Kth Level Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
5 min read
Print Ancestors of a given node in Binary Tree Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree. For example, if the given tree is following Binary Tree and the key is 7, then your function should print 4, 2, and 1. 1 / \ 2 3 / \ 4 5 / 7Recommended PracticeAncestors in Binary TreeT
13 min read
Count the number of nodes at given level in a tree using BFS. Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traver
9 min read
Relationship between number of nodes and height of binary tree Binary Tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and traversal.Prerequ
2 min read