We have discussed two solutions in the articles below. Print level order traversal line by line | Set 1 Level order traversal line by line | Set 2 (Using Two Queues) In this post, a different approach using one queue is discussed. First insert the root and a null element into the queue. This null element acts as a delimiter. Next, pop from the top of the queue and add its left and right nodes to the end of the queue and then print at the top of the queue. Continue this process till the queues become empty.
C++
/* C++ program to print levels
line by line */
#include <bits/stdc++.h>
usingnamespacestd;
// A Binary Tree Node
structnode
{
structnode *left;
intdata;
structnode *right;
};
// Function to do level order
// traversal line by line
voidlevelOrder(node *root)
{
if(root == NULL) return;
// Create an empty queue for
// level order traversal
queue<node *> q;
// to store front element of
// queue.
node *curr;
// Enqueue Root and NULL node.
q.push(root);
q.push(NULL);
while(q.size() > 1)
{
curr = q.front();
q.pop();
// condition to check
// occurrence of next
// level.
if(curr == NULL)
{
q.push(NULL);
cout << "\n";
}
else{
// pushing left child of
// current node.
if(curr->left)
q.push(curr->left);
// pushing right child of
// current node.
if(curr->right)
q.push(curr->right);
cout << curr->data << " ";
}
}
}
// Utility function to create a
// new tree node
node* newNode(intdata)
{
node *temp = newnode;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
returntemp;
}
// Driver program to test above
// functions
intmain()
{
// Let us create binary tree
// shown above
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
levelOrder(root);
return0;
}
// This code is contributed by
// Nikhil Jindal.
Java
// Java program to do level order
// traversal line by line
importjava.util.LinkedList;
importjava.util.Queue;
publicclassGFG {
staticclassNode {
intdata;
Node left;
Node right;
Node(intdata) {
this.data = data;
left = null;
right = null;
}
}
// Prints level order traversal line
// by line using two queues.
staticvoidlevelOrder(Node root) {
if(root == null)
return;
Queue<Node> q = newLinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Pushing delimiter into the queue.
q.add(null);
// Executing loop till queue becomes
// empty
while(!q.isEmpty()) {
Node curr = q.poll();
// condition to check the
// occurrence of next level
if(curr == null) {
if(!q.isEmpty()) {
q.add(null);
System.out.println();
}
} else{
// Pushing left child current node
if(curr.left != null)
q.add(curr.left);
// Pushing right child current node
if(curr.right != null)
q.add(curr.right);
System.out.print(curr.data + " ");
}
}
}
// Driver function
publicstaticvoidmain(String[] args) {
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.right = newNode(6);
levelOrder(root);
}
}
// This code is Contributed by Rishabh Jindal
Python3
# Python3 program to print levels
# line by line
fromcollections importdeque as queue
# A Binary Tree Node
classNode:
def__init__(self, key):
self.data =key
self.left =None
self.right =None
# Function to do level order
# traversal line by line
deflevelOrder(root):
if(root ==None):
return
# Create an empty queue for
# level order traversal
q =queue()
# To store front element of
# queue.
#node *curr
# Enqueue Root and None node.
q.append(root)
q.append(None)
while(len(q) > 1):
curr =q.popleft()
# q.pop()
# Condition to check
# occurrence of next
# level.
if(curr ==None):
q.append(None)
print()
else:
# Pushing left child of
# current node.
if(curr.left):
q.append(curr.left)
# Pushing right child of
# current node.
if(curr.right):
q.append(curr.right)
print(curr.data, end=" ")
# Driver code
if__name__ =='__main__':
# Let us create binary tree
# shown above
root =Node(1)
root.left =Node(2)
root.right =Node(3)
root.left.left =Node(4)
root.left.right =Node(5)
root.right.right =Node(6)
levelOrder(root)
# This code is contributed by mohit kumar 29
C#
// C# program to do level order
// traversal line by line
usingSystem;
usingSystem.Collections;
classGFG
{
publicclassNode
{
publicintdata;
publicNode left;
publicNode right;
publicNode(intdata)
{
this.data = data;
left = null;
right = null;
}
}
// Prints level order traversal line
// by line using two queues.
staticvoidlevelOrder(Node root)
{
if(root == null)
return;
Queue q = newQueue();
// Pushing root node into the queue.
q.Enqueue(root);
// Pushing delimiter into the queue.
q.Enqueue(null);
// Executing loop till queue becomes
// empty
while(q.Count>0)
{
Node curr = (Node)q.Peek();
q.Dequeue();
// condition to check the
// occurrence of next level
if(curr == null)
{
if(q.Count > 0)
{
q.Enqueue(null);
Console.WriteLine();
}
}
else
{
// Pushing left child current node
if(curr.left != null)
q.Enqueue(curr.left);
// Pushing right child current node
if(curr.right != null)
q.Enqueue(curr.right);
Console.Write(curr.data + " ");
}
}
}
// Driver code
staticpublicvoidMain(String []args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.right = newNode(6);
levelOrder(root);
}
}
// This code is Contributed by Arnab Kundu
Javascript
<script>
// Javascript program to do level order
// traversal line by line
class Node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
// Prints level order traversal line
// by line using two queues.
functionlevelOrder(root)
{
if(root == null)
return;
let q= [];
// Pushing root node into the queue.
q.push(root);
// Pushing delimiter into the queue.
q.push(null);
// Executing loop till queue becomes
// empty
while(q.length!=0) {
let curr = q.shift();
// condition to check the
// occurrence of next level
if(curr == null) {
if(q.length!=0) {
q.push(null);
document.write("<br>");
}
}
else{
// Pushing left child current node
if(curr.left != null)
q.push(curr.left);
// Pushing right child current node
if(curr.right != null)
q.push(curr.right);
document.write(curr.data + " ");
}
}
}
// Driver 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.right = newNode(6);
levelOrder(root);
// This code is contributed by patel2127
</script>
Output
1
2 3
4 5 6
Time Complexity: O(n) Auxiliary Space: O(n) for queue, where n is no of nodes of binary tree
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 neveropen!