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++
#include<bits/stdc++.h>
using namespace std;
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;
}
void printNodes(Node* root, int start, int end){
if (root == NULL) return ;
queue<Node*> queue;
queue.push(root);
Node *curr = NULL;
int level = 0;
while (!queue.empty()) {
level++;
int size = queue.size();
while (size != 0){
curr = queue.front();
queue.pop();
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" ;
}
}
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, end = 3;
printNodes(root, start, end);
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
static class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
Node root;
public BinaryTree()
{
root = null ;
}
void printNodes(Node root, int start, int end)
{
if (root == null ) {
return ;
}
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
Node curr = null ;
int level = 0 ;
while (!queue.isEmpty()) {
level++;
int size = queue.size();
while (size != 0 ) {
curr = queue.poll();
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( "" );
};
}
}
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 );
int start = 2 , end = 3 ;
tree.printNodes(tree.root, start, end);
}
}
|
Python3
class newNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def printNodes(root, start, end):
if (root = = None ):
return
q = []
q.append(root)
curr = None
level = 0
while ( len (q)):
level + = 1
size = len (q)
while (size ! = 0 ) :
curr = q[ 0 ]
q.pop( 0 )
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 ("")
if __name__ = = '__main__' :
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)
|
C#
using System;
using System.Collections.Generic;
public class BinaryTree
{
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
Node root;
public BinaryTree()
{
root = null ;
}
void printNodes(Node root, int start, int end)
{
if (root == null )
{
return ;
}
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
Node curr = null ;
int level = 0;
while (queue.Count >0)
{
level++;
int size = queue.Count;
while (size != 0)
{
curr = queue.Peek();
queue.Dequeue();
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( "" );
};
}
}
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);
int start = 2, end = 3;
tree.printNodes(tree.root, start, end);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
let root = null ;
function printNodes(root, start, end)
{
if (root == null ) {
return ;
}
let queue = [];
queue.push(root);
let curr = null ;
let level = 0;
while (queue.length > 0) {
level++;
let size = queue.length;
while (size != 0) {
curr = queue[0];
queue.shift();
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);
let start = 2, end = 3;
printNodes(tree.root, start, end);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* left;
struct Node* right;
};
Node* newNode( int data){
Node *new_node = new Node();
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
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);
}
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;
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;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
Node newNode( int data) {
Node new_node = new Node(data);
new_node.left = null ;
new_node.right = null ;
return new_node;
}
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 );
}
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>());
}
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
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def newNode(data):
return Node(data)
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 )
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)
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#
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;
public Node NewNode( int data)
{
Node newNode = new Node(data);
newNode.left = null ;
newNode.right = null ;
return newNode;
}
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()
{
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 >());
}
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();
}
}
}
|
Javascript
class Node{
constructor(data){
this .data = data;
this .left = null ;
this .right = null ;
}
}
function newNode(data){
return new Node(data);
}
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);
}
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] = [];
}
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>" );
}
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
27 Mar, 2023
Like Article
Save Article