Given root of a binary tree, The task is to print level order traversal in a way that nodes of all levels are printed in separate lines.
Examples:
Input:

Output:
20
8 22
4 12
10 14
Input:
1
/ \
2 3
/ \
4 5
Output:
1
2 3
4 5
Note: that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels on different lines.
Approach: Below is the idea to solve the problem:
A simple solution is to print using the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel().
Find height of tree and run depth first search and maintain current height, print nodes for every height from root and for 1 to height.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node *left, *right;
};
void printCurrentLevel(node* root, int level);
int height(node* node);
node* newNode( int data);
void printGivenLevel( struct node* root, int level)
{
if (root == NULL)
return ;
if (level == 1)
printf ( "%d " , root->data);
else if (level > 1) {
printGivenLevel(root->left, level - 1);
printGivenLevel(root->right, level - 1);
}
}
void printLevelOrder( struct node* root)
{
int h = height(root);
int i;
for (i = 1; i <= h; i++) {
printGivenLevel(root, i);
printf ( "\n" );
}
}
int height(node* node)
{
if (node == NULL)
return 0;
else {
int lheight = height(node->left);
int rheight = height(node->right);
if (lheight > rheight) {
return (lheight + 1);
}
else {
return (rheight + 1);
}
}
}
node* newNode( int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Level Order traversal of binary tree is \n" ;
printLevelOrder(root);
return 0;
}
|
Java
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
public BinaryTree() { root = null ; }
int height(Node root)
{
if (root == null )
return 0 ;
else {
int lheight = height(root.left);
int rheight = height(root.right);
if (lheight > rheight)
return (lheight + 1 );
else
return (rheight + 1 );
}
}
void printGivenLevel(Node root, int level)
{
if (root == null )
return ;
if (level == 1 ) {
System.out.print(root.data + " " );
}
else if (level > 1 ) {
printGivenLevel(root.left, level - 1 );
printGivenLevel(root.right, level - 1 );
}
}
void printLevelOrder()
{
int h = height(root);
int i;
for (i = 1 ; i <= h; i++) {
printGivenLevel(root, i);
System.out.print(System.lineSeparator());
}
}
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 );
System.out.println(
"Level order traversal of binary tree is " );
tree.printLevelOrder();
}
}
|
Python3
class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def printlevelorder(root):
h = height(root)
for i in range ( 1 , h + 1 ):
printGivenLevel(root, i)
print ()
def printGivenLevel(root, level):
if root is None :
return root
if level = = 1 :
print (root.data, end = ' ' )
elif level > 1 :
printGivenLevel(root.left, level - 1 )
printGivenLevel(root.right, level - 1 )
def height(node):
if node is None :
return 0
else :
lheight = height(node.left)
rheight = height(node.right)
if lheight > rheight:
return lheight + 1
else :
return rheight + 1
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
print ( "Level order traversal of binary tree is -" )
printlevelorder(root)
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class GFG {
public Node root;
public void BinaryTree() { root = null ; }
public virtual void printLevelOrder()
{
int h = height(root);
int i;
for (i = 1; i <= h; i++) {
printGivenLevel(root, i);
Console.WriteLine();
}
}
public virtual int height(Node root)
{
if (root == null ) {
return 0;
}
else {
int lheight = height(root.left);
int rheight = height(root.right);
if (lheight > rheight) {
return (lheight + 1);
}
else {
return (rheight + 1);
}
}
}
static void printGivenLevel(Node root, int level)
{
if (root == null )
return ;
if (level == 1) {
Console.Write(root.data + " " );
}
else if (level > 1) {
printGivenLevel(root.left, level - 1);
printGivenLevel(root.right, level - 1);
}
}
public static void Main( string [] args)
{
GFG tree = new GFG();
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);
Console.WriteLine( "Level order traversal "
+ "of binary tree is " );
tree.printLevelOrder();
}
}
|
Javascript
function printGivenLevel(root, level)
{
if (root == null )
return ;
if (level == 1)
document.write(root.data);
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}
|
Output
Level Order traversal of binary tree is
1
2 3
4 5
Time complexity: O(N2)
Auxiliary Space: O(N)
The idea is to keep a queue that stores nodes of the current level. Starting from root, calculate the size of queue sz and for each one of sz nodes enqueue its children to queue and print the node. After printing sz nodes of every iteration print a line break.
Follow the below steps to Implement the idea:
- Initialize a queue q. Push root in q.
- while q is not empty
- Create a variable nodeCount = q.size().
- while (nodeCount > 0)
- Create temporary node node *node = q.front() and print node->data.
- Pop front element from q.
- If node->left != NULL push node->left in q.
- If node->right != NULL push node->right in q.
- Print endline.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <queue>
using namespace std;
struct node {
struct node* left;
int data;
struct node* right;
};
void printLevelOrder(node* root)
{
if (root == NULL)
return ;
queue<node*> q;
q.push(root);
while (q.empty() == false ) {
int nodeCount = q.size();
while (nodeCount > 0) {
node* node = q.front();
cout << node->data << " " ;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}
node* newNode( int data)
{
node* temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printLevelOrder(root);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class LevelOrder {
static class Node {
int data;
Node left;
Node right;
Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
static void printLevelOrder(Node root)
{
if (root == null )
return ;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while ( true ) {
int nodeCount = q.size();
if (nodeCount == 0 )
break ;
while (nodeCount > 0 ) {
Node node = q.peek();
System.out.print(node.data + " " );
q.remove();
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
nodeCount--;
}
System.out.println();
}
}
public static void main(String[] args)
{
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 );
printLevelOrder(root);
}
}
|
Python3
class newNode:
def __init__( self , data):
self .val = data
self .left = None
self .right = None
def printLevelOrder(root):
if root is None :
return
q = []
q.append(root)
while q:
count = len (q)
while count > 0 :
temp = q.pop( 0 )
print (temp.val, end = ' ' )
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
count - = 1
print ( ' ' )
root = newNode( 1 )
root.left = newNode( 2 )
root.right = newNode( 3 )
root.left.left = newNode( 4 )
root.left.right = newNode( 5 )
printLevelOrder(root)
|
C#
using System;
using System.Collections.Generic;
public class LevelOrder {
class Node {
public int data;
public Node left;
public Node right;
public Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
static void printLevelOrder(Node root)
{
if (root == null )
return ;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while ( true ) {
int nodeCount = q.Count;
if (nodeCount == 0)
break ;
while (nodeCount > 0) {
Node node = q.Peek();
Console.Write(node.data + " " );
q.Dequeue();
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
nodeCount--;
}
Console.WriteLine();
}
}
public static void Main(String[] args)
{
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);
printLevelOrder(root);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function printLevelOrder(root)
{
if (root == null )
return ;
let q = [];
q.push(root);
while ( true )
{
let nodeCount = q.length;
if (nodeCount == 0)
break ;
while (nodeCount > 0)
{
let node = q[0];
document.write(node.data + " " );
q.shift();
if (node.left != null )
q.push(node.left);
if (node.right != null )
q.push(node.right);
nodeCount--;
}
document.write( "</br>" );
}
}
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);
printLevelOrder(root);
</script>
|
Time complexity: O(N) where n is no of nodes of binary tree
Auxiliary Space: O(N) for queue
Time complexity of this method is O(n) where n is number of nodes in given binary tree.
Level order traversal line by line | Set 2 (Using Two Queues)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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 :
22 Sep, 2022
Like Article
Save Article