Print level order traversal line by line | Set 1

24 Jun, 2022
Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.For example consider the following tree  
Example 1:
Output for above tree should be
20
8 22
4 12
10 14

Example 2:
          1
       /     \
      2       3
    /   \       \
   4     5       6
        /  \     /
       7    8   9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
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 in different lines.A simple solution is to print use the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel(). 
C++
Java
Python3
C#
Javascript
/* Function to line by line print level order traversal a tree*/void printLevelOrder(struct node* root){    int h = height(root);    int i;    for (i=1; i<=h; i++)    {        printGivenLevel(root, i);        printf("\n");    }} /* Print nodes at a given level */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);    }}
/* Function to line by line print level order traversal a tree*/static void printLevelOrder(Node root){    int h = height(root);    int i;    for (i=1; i<=h; i++)    {        printGivenLevel(root, i);        System.out.println();    }}/* Print nodes at a given level */void printGivenLevel(Node root, int level){    if (root == null)        return;    if (level == 1)        System.out.println(root.data);    else if (level > 1)    {        printGivenLevel(root.left, level-1);        printGivenLevel(root.right, level-1);    }}
# Python3 program for above approach def printlevelorder(root):    h = height(root)    for i in range(1, h + 1):        givenspirallevel(root, i) def printGivenLevel(root, level):    if root is None:        return root         if level == 1:        print(root.val, end = ' ')    elif level > 1:        printGivenLevel(root.left, level - 1)        printGivenLevel(root.right, level - 1) # This code is contributed by Praveen kumar
/* Print nodes at a given level */static void printGivenLevel(Node root, int level){    if (root == null)        return;    if (level == 1)        Console.WriteLine(root.data);    else if (level > 1)    {        printGivenLevel(root.left, level-1);        printGivenLevel(root.right, level-1);    }}
/* Print nodes at a given level */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);    }}
Time complexity: O(n2)
Auxiliary Space: O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
How to modify the iterative level order traversal (Method 2 of this) to levels line by line? The idea is similar to this post. We count the nodes at current level. And for every node, we enqueue its children to queue.  
C++
Java
Python3
C#
Javascript
/* Iterative program to print levels line by line */#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct node{    struct node *left;    int data;    struct node *right;}; // Iterative method to do level order traversal// line by linevoid printLevelOrder(node *root){    // Base Case    if (root == NULL) return;     // Create an empty queue for level order traversal    queue<node *> q;     // Enqueue Root and initialize height    q.push(root);     while (q.empty() == false)    {        // nodeCount (queue size) indicates number        // of nodes at current level.        int nodeCount = q.size();         // Dequeue all nodes of current level and        // Enqueue all nodes of next level        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;    }} // Utility function to create a new tree nodenode* newNode(int data){    node *temp = new node;    temp->data = data;    temp->left = NULL;    temp->right = NULL;    return temp;} // Driver program to test above functionsint 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);     printLevelOrder(root);    return 0;}
/* An Iterative Java program to print levels line by line */ import java.util.LinkedList;import java.util.Queue; public class LevelOrder{    // A Binary Tree Node    static class Node    {        int data;        Node left;        Node right;                 // constructor        Node(int data){            this.data = data;            left = null;            right =null;        }    }         // Iterative method to do level order traversal line by line    static void printLevelOrder(Node root)    {        // Base Case        if(root == null)            return;                 // Create an empty queue for level order traversal        Queue<Node> q =new LinkedList<Node>();                 // Enqueue Root and initialize height        q.add(root);                          while(true)        {                         // nodeCount (queue size) indicates number of nodes            // at current level.            int nodeCount = q.size();            if(nodeCount == 0)                break;                         // Dequeue all nodes of current level and Enqueue all            // nodes of next level            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();        }    }         // Driver program to test above functions    public static void main(String[] args)    {        // Let us create binary tree shown in above diagram       /*               1                   /     \                  2       3                /   \       \               4     5       6        */                 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);                 printLevelOrder(root);     } }//This code is contributed by Sumit Ghosh
# Python3 program for above approachclass newNode:    def __init__(self, data):        self.val = data        self.left = None        self.right = None         # Iterative method to do level order traversal# line by linedef printLevelOrder(root):         # Base case    if root is None:        return    # Create an empty queue for level order traversal    q = []         # Enqueue root and initialize height    q.append(root)             while q:             # nodeCount (queue size) indicates number        # of nodes at current level.        count = len(q)                 # Dequeue all nodes of current level and        # Enqueue all nodes of next level        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(' ')         # Driver Coderoot = 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); printLevelOrder(root); # This code is contributed by Praveen kumar
/* An Iterative C# program to printlevels line by line */using System;using System.Collections.Generic; public class LevelOrder{    // A Binary Tree Node    class Node    {        public int data;        public Node left;        public Node right;                 // constructor        public Node(int data)        {            this.data = data;            left = null;            right =null;        }    }         // Iterative method to do level order    // traversal line by line    static void printLevelOrder(Node root)    {        // Base Case        if(root == null)            return;                 // Create an empty queue for level        // order traversal        Queue<Node> q =new Queue<Node>();                 // Enqueue Root and initialize height        q.Enqueue(root);                 while(true)        {                         // nodeCount (queue size) indicates            // number of nodes at current level.            int nodeCount = q.Count;            if(nodeCount == 0)                break;                         // Dequeue all nodes of current level            // and Enqueue all nodes of next level            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();        }    }         // Driver Code    public static void Main(String[] args)    {        // Let us create binary tree shown        // in above diagram        /*         1                    / \                    2 3                    / \ \                4 5 6            */        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);                 printLevelOrder(root);    }} // This code is contributed 29AjayKumar
<script>     /* An Iterative Javascript program to       print levels line by line */         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // Iterative method to do level order traversal line by line    function printLevelOrder(root)    {        // Base Case        if(root == null)            return;                  // Create an empty queue for level order traversal        let q = [];                  // Enqueue Root and initialize height        q.push(root);                            while(true)        {                          // nodeCount (queue size) indicates number of nodes            // at current level.            let nodeCount = q.length;            if(nodeCount == 0)                break;                          // Dequeue all nodes of current level and Enqueue all            // nodes of next level            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 us create binary tree shown in above diagram    /*                  1                     /     \                    2       3                  /   \       \                 4     5       6          */     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);    root.right.right = new Node(6);     printLevelOrder(root);     </script>
Output:  
1
2 3
4 5 6
Time complexity: O(n) where n is no of nodes of binary tree
Auxiliary Space: O(n) for queue
 
Print level order traversal line by line | Set 1 | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint level order traversal line by line | Set 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WheCF0n2Hl4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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 
29AjayKumar
princiraj1992
mepky
anikakapoor
noob2000
mukesh07
technophpfij
Amazon
cpp-queue
Hike
Microsoft
Morgan Stanley
tree-level-order
Tree
Morgan Stanley
Amazon
Microsoft
Hike
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.