Level order traversal line by line | Set 3 (Using One Queue)

Given a Binary Tree, print the nodes level wise, each level on a new line.

Example

Output:
1
2 3
4 5

We have discussed two solution in below articles.
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 the top of the queue. Continue this process till the queues become empty.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

/* CPP program to print levels 
line by line */
#include <bits/stdc++.h>
using namespace std;
  
// A Binary Tree Node
struct node
{
    struct node *left;
    int data;
    struct node *right;
};
  
// Function to do level order
// traversal line by line
void levelOrder(node *root)
{
    if (root == NULL) return;
  
    // Create an empty queue for
    // level order tarversal
    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 rigth child of
            // current node.
            if(curr->right)
            q.push(curr->right);
              
            cout << curr->data << " ";
        }
    }
}
  
// Utility function to create a
// new tree node
node* newNode(int data)
{
    node *temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
  
// Driver program to test above
// functions
int main()
{
      
    // 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);
    return 0;
}
  
// This code is contributed by
// Nikhil Jindal.

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to do level order
// traversal line by line
import java.util.LinkedList;
import java.util.Queue;
  
public class GFG {
  static class Node {
    int data;
    Node left;
    Node right;
  
    Node(int data) {
      this.data = data;
      left = null;
      right = null;
    }
  }
  
  // Prints level order traversal line
  // by line using two queues.
  static void levelOrder(Node root) {
    if (root == null)
      return;
  
    Queue<Node> q = new LinkedList<>();
  
    // 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
      // occurence 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
  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);
    root.right.right = new Node(6);
  
    levelOrder(root);
  }
}
  
// This code is Contributed by Rishabh Jindal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to do level order
// traversal line by line
using System;
using System.Collections;
  
class GFG 
{
public class Node 
{
    public int data;
    public Node left;
    public Node right;
  
    public Node(int data) 
    {
        this.data = data;
        left = null;
        right = null;
    }
}
  
// Prints level order traversal line
// by line using two queues.
static void levelOrder(Node root) 
{
    if (root == null)
    return;
  
    Queue q = new Queue();
  
    // 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
        // occurence 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
static public 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);
    root.right.right = new Node(6);
  
    levelOrder(root);
}
}
  
// This code is Contributed by Arnab Kundu

chevron_right



Output :

1
2 3
4 5 6

Time Complexity : O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nik1996, andrew1234



Article Tags :
Practice Tags :


7


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.