Saturday, December 28, 2024
Google search engine
HomeData Modelling & AIPrint level order traversal line by line | Set 1

Print level order traversal line by line | Set 1

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++




/* Function to line by line print level order traversal a
 * tree*/
 
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data,
pointer to left child
and a pointer to right child */
class node {
public:
    int data;
    node *left, *right;
};
 
/* Function prototypes */
void printCurrentLevel(node* root, int level);
int height(node* node);
node* newNode(int data);
 
/* 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);
    }
}
 
void printLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i = 1; i <= h; i++) {
        printGivenLevel(root, i);
        printf("\n");
    }
}
 
/* Compute the "height" of a tree -- the number of
 nodes along the longest path from the root node
 down to the farthest leaf node.*/
int height(node* node)
{
    if (node == NULL)
        return 0;
    else {
        /* compute the height of each subtree */
        int lheight = height(node->left);
        int rheight = height(node->right);
 
        /* use the larger one */
        if (lheight > rheight) {
            return (lheight + 1);
        }
        else {
            return (rheight + 1);
        }
    }
}
 
/* Helper function that allocates
a new node with the given data and
NULL left and right pointers. */
node* newNode(int data)
{
    node* Node = new node();
    Node->data = data;
    Node->left = NULL;
    Node->right = NULL;
 
    return (Node);
}
 
/* Driver code*/
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




/* Function to line by line print level order traversal a
 * tree*/
/* Class containing left and right child of current
node and key value*/
 
/* Class containing left and right child of current
node and key value*/
class Node {
    int data;
    Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
    // Root of the Binary Tree
    Node root;
 
    public BinaryTree() { root = null; }
 
    /* Compute the "height" of a tree -- the number of
    nodes along the longest path from the root node
    down to the farthest leaf node.*/
    int height(Node root)
    {
        if (root == null)
            return 0;
        else {
            /* compute height of each subtree */
            int lheight = height(root.left);
            int rheight = height(root.right);
 
            /* use the larger one */
            if (lheight > rheight)
                return (lheight + 1);
            else
                return (rheight + 1);
        }
    }
 
    /* Print nodes at a given level */
    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);
        }
    }
 
    /* function to print level order traversal of tree*/
    void printLevelOrder()
    {
        int h = height(root);
        int i;
        for (i = 1; i <= h; i++) {
            printGivenLevel(root, i);
            System.out.print(System.lineSeparator());
        }
    }
 
    /* Driver program to test above functions */
    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




# Python3 program for above approach
 
 
class Node:
 
    # A utility function to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
 
# Function to print level order traversal of tree
 
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)
 
 
""" Compute the height of a tree--the number of nodes
 along the longest path from the root node down to
 the farthest leaf node
"""
 
 
def height(node):
    if node is None:
        return 0
    else:
        # Compute the height of each subtree
        lheight = height(node.left)
        rheight = height(node.right)
 
        # Use the larger one
        if lheight > rheight:
            return lheight+1
        else:
            return rheight+1
 
 
# Driver program to test above function
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)
 
# Contributed by Praveen kumar & Vivek Radhakrishna


C#




/* Print nodes at a given level */
 
using System;
 
/* Class containing left and right
   child of current node and key value*/
public class Node {
    public int data;
    public Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class GFG {
    // Root of the Binary Tree
    public Node root;
 
    public void BinaryTree() { root = null; }
 
    /* function to print level order
       traversal of tree*/
    public virtual void printLevelOrder()
    {
        int h = height(root);
        int i;
        for (i = 1; i <= h; i++) {
            printGivenLevel(root, i);
            Console.WriteLine();
        }
    }
 
    /* Compute the "height" of a tree --
    the number of nodes along the longest
    path from the root node down to the
    farthest leaf node.*/
    public virtual int height(Node root)
    {
        if (root == null) {
            return 0;
        }
        else {
            /* compute height of each subtree */
            int lheight = height(root.left);
            int rheight = height(root.right);
 
            /* use the larger one */
            if (lheight > rheight) {
                return (lheight + 1);
            }
            else {
                return (rheight + 1);
            }
        }
    }
 
    /* Print nodes at the current level */
    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);
        }
    }
 
    // Driver Code
    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




/* 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);
    }
}


Output

Level Order traversal of binary tree is 
1 
2 3 
4 5 

Time complexity: O(N2)
Auxiliary Space: O(N)

Print level order traversal line by line using iterative level order traversal 

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++




/* Iterative program to print levels line by line */
#include <iostream>
#include <queue>
using namespace std;
 
// A Binary Tree Node
struct node {
    struct node* left;
    int data;
    struct node* right;
};
 
// Iterative method to do level order traversal
// line by line
void 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 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);
 
    printLevelOrder(root);
    return 0;
}


Java




/* 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);
 
        printLevelOrder(root);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program for above approach
class newNode:
    def __init__(self, data):
        self.val = data
        self.left = None
        self.right = None
 
# Iterative method to do level order traversal
# line by line
 
 
def 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 Code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
 
printLevelOrder(root)
 
# This code is contributed by Praveen kumar


C#




/* An Iterative C# program to print
levels 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);
 
        printLevelOrder(root);
    }
}
 
// This code is contributed 29AjayKumar


Javascript




<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);
 
    printLevelOrder(root);
     
</script>


Output

1 
2 3 
4 5 

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 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments