Level Order Traversal technique is defined as a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level.
Example:
Input:
Output:
1
2 3
4 5
How does Level Order Traversal work?
The main idea of level order traversal is to traverse all the nodes of a lower level before moving to any of the nodes of a higher level. This can be done in any of the following ways:Â
- the naive one (finding the height of the tree and traversing each level and printing the nodes of that level)
- efficiently using a queue.
Level Order Traversal (Naive approach):
Find height of tree. Then for each level, run a recursive function by maintaining current height. Whenever the level of a node matches, print that node.
Below is the implementation of the above approach:
C
// Recursive C program for level// order traversal of Binary Tree#include <stdio.h>#include <stdlib.h>Â
// A binary tree node has data,// pointer to left child// and a pointer to right childstruct node {Â Â Â Â int data;Â Â Â Â struct node *left, *right;};Â
// Function prototypesvoid printCurrentLevel(struct node* root, int level);int height(struct node* node);struct node* newNode(int data);Â
// Function to print level order traversal a treevoid printLevelOrder(struct node* root){Â Â Â Â int h = height(root);Â Â Â Â int i;Â Â Â Â for (i = 1; i <= h; i++)Â Â Â Â Â Â Â Â printCurrentLevel(root, i);}Â
// Print nodes at a current levelvoid printCurrentLevel(struct node* root, int level){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â Â Â Â if (level == 1)Â Â Â Â Â Â Â Â printf("%d ", root->data);Â Â Â Â else if (level > 1) {Â Â Â Â Â Â Â Â printCurrentLevel(root->left, level - 1);Â Â Â Â Â Â Â Â printCurrentLevel(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 nodeint height(struct 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.struct node* newNode(int data){    struct node* node        = (struct node*)malloc(sizeof(struct node));    node->data = data;    node->left = NULL;    node->right = NULL;Â
    return (node);}Â
// Driver program to test above functionsint main(){Â Â Â Â struct node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->left->right = newNode(5);Â
    printf("Level Order traversal of binary tree is \n");    printLevelOrder(root);Â
    return 0;} |
C++
// Recursive CPP program for level// order traversal of Binary Tree#include <bits/stdc++.h>using namespace std;Â
// A binary tree node has data,// pointer to left child// and a pointer to right childclass node {public:Â Â Â Â int data;Â Â Â Â node *left, *right;};Â
// Function prototypesvoid printCurrentLevel(node* root, int level);int height(node* node);node* newNode(int data);Â
// Function to print level order traversal a treevoid printLevelOrder(node* root){Â Â Â Â int h = height(root);Â Â Â Â int i;Â Â Â Â for (i = 1; i <= h; i++)Â Â Â Â Â Â Â Â printCurrentLevel(root, i);}Â
// Print nodes at a current levelvoid printCurrentLevel(node* root, int level){Â Â Â Â if (root == NULL)Â Â Â Â Â Â Â Â return;Â Â Â Â if (level == 1)Â Â Â Â Â Â Â Â cout << root->data << " ";Â Â Â Â else if (level > 1) {Â Â Â Â Â Â Â Â printCurrentLevel(root->left, level - 1);Â Â Â Â Â Â Â Â printCurrentLevel(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.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 codeint 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;}Â
// This code is contributed by rathbhupendra |
Java
// Recursive Java program for level// order traversal of Binary TreeÂ
// Class containing left and right child of current// node and key valueclass 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; }Â
    // Function to print level order traversal of tree    void printLevelOrder()    {        int h = height(root);        int i;        for (i = 1; i <= h; i++)            printCurrentLevel(root, i);    }Â
    // 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 the current level    void printCurrentLevel(Node root, int level)    {        if (root == null)            return;        if (level == 1)            System.out.print(root.data + " ");        else if (level > 1) {            printCurrentLevel(root.left, level - 1);            printCurrentLevel(root.right, level - 1);        }    }Â
    // 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
# Recursive Python program for level# order traversal of Binary TreeÂ
Â
# A node structureclass 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 treedef printLevelOrder(root):    h = height(root)    for i in range(1, h+1):        printCurrentLevel(root, i)Â
Â
# Print nodes at a current leveldef printCurrentLevel(root, level):    if root is None:        return    if level == 1:        print(root.data, end=" ")    elif level > 1:        printCurrentLevel(root.left, level-1)        printCurrentLevel(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 nodedef 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 functionif __name__ == '__main__':Â Â Â Â 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)Â
# This code is contributed by Nikhil Kumar Singh(nickzuck_007) |
C#
// Recursive c# program for level// order traversal of Binary Treeusing System;Â
// Class containing left and right// child of current node and key valuepublic 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++) {            printCurrentLevel(root, i);        }    }Â
    // 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    public virtual void printCurrentLevel(Node root,                                          int level)    {        if (root == null) {            return;        }        if (level == 1) {            Console.Write(root.data + " ");        }        else if (level > 1) {            printCurrentLevel(root.left, level - 1);            printCurrentLevel(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();    }}Â
// This code is contributed by Shrikant13 |
Javascript
// Recursive javascript program for level// order traversal of Binary TreeÂ
// Class containing left and right child of current// node and key value class Node {        constructor(val) {            this.data = val;            this.left = null;            this.right = null;        }    }Â
Â
    // Root of the Binary Tree    var root= null;         // Function to print level order traversal of tree    function printLevelOrder() {        var h = height(root);        var i;        for (i = 1; i <= h; i++)            printCurrentLevel(root, i);    }Â
    // Compute the "height" of a tree -- the number     // of nodes along the longest path    // from the root node down to the farthest leaf node.    function height(root) {        if (root == null)            return 0;        else {            // Compute height of each subtree            var lheight = height(root.left);            var rheight = height(root.right);Â
            // Use the larger one            if (lheight > rheight)                return (lheight + 1);            else                return (rheight + 1);        }    }Â
    // Print nodes at the current level    function printCurrentLevel(root , level) {        if (root == null)            return;        if (level == 1)            console.log(root.data + " ");        else if (level > 1) {            printCurrentLevel(root.left, level - 1);            printCurrentLevel(root.right, level - 1);        }    }Â
    // Driver program to test above functions             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);Â
       console.log("Level order traversal of binary tree is ");       printLevelOrder();Â
// This code is contributed by umadevi9616 |
Level Order traversal of binary tree is 1 2 3 4 5
Time Complexity: O(N2), where N is the number of nodes in the skewed tree.
Auxiliary Space: O(1) If the recursion stack is considered the space used is O(N).
Level Order Traversal using Queue
We need to visit the nodes in a lower level before any node in a higher level, this idea is quite similar to that of a queue. Push the nodes of a lower level in the queue. When any node is visited, pop that node from the queue and push the child of that node in the queue.
This ensures that the node of a lower level are visited prior to any node of a higher level.
Below is the Implementation of the above approach:
C
// Iterative Queue based C program// to do level order traversal// of Binary Tree#include <stdio.h>#include <stdlib.h>#define MAX_Q_SIZE 500Â
// A binary tree node has data,// pointer to left child// and a pointer to right childstruct node {Â Â Â Â int data;Â Â Â Â struct node* left;Â Â Â Â struct node* right;};Â
// Function prototypesstruct node** createQueue(int*, int*);void enQueue(struct node**, int*, struct node*);struct node* deQueue(struct node**, int*);Â
// Given a binary tree, print its nodes in level order// using array for implementing queuevoid printLevelOrder(struct node* root){Â Â Â Â int rear, front;Â Â Â Â struct node** queue = createQueue(&front, &rear);Â Â Â Â struct node* temp_node = root;Â
    while (temp_node) {        printf("%d ", temp_node->data);Â
        // Enqueue left child        if (temp_node->left)            enQueue(queue, &rear, temp_node->left);Â
        // Enqueue right child        if (temp_node->right)            enQueue(queue, &rear, temp_node->right);Â
        // Dequeue node and make it temp_node        temp_node = deQueue(queue, &front);    }}Â
// Utility functionsstruct node** createQueue(int* front, int* rear){Â Â Â Â struct node** queue = (struct node**)malloc(Â Â Â Â Â Â Â Â sizeof(struct node*) * MAX_Q_SIZE);Â
    *front = *rear = 0;    return queue;}Â
void enQueue(struct node** queue, int* rear,             struct node* new_node){    queue[*rear] = new_node;    (*rear)++;}Â
struct node* deQueue(struct node** queue, int* front){Â Â Â Â (*front)++;Â Â Â Â return queue[*front - 1];}Â
// Helper function that allocates a new node with the// given data and NULL left and right pointers.struct node* newNode(int data){    struct node* node        = (struct node*)malloc(sizeof(struct node));    node->data = data;    node->left = NULL;    node->right = NULL;Â
    return (node);}Â
// Driver program to test above functionsint main(){Â Â Â Â struct node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->left->right = newNode(5);Â
    printf("Level Order traversal of binary tree is \n");    printLevelOrder(root);Â
    return 0;} |
C++
// C++ program to print level order traversal#include <bits/stdc++.h>using namespace std;Â
// A Binary Tree Nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node *left, *right;};Â
// Iterative method to find height of Binary Treevoid 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) {                 // Print front of queue and remove it from queue        Node* node = q.front();        cout << node->data << " ";        q.pop();Â
        // Enqueue left child        if (node->left != NULL)            q.push(node->left);Â
        // Enqueue right child        if (node->right != NULL)            q.push(node->right);    }}Â
// Utility function to create a new tree nodeNode* newNode(int data){Â Â Â Â Node* temp = new Node;Â Â Â Â temp->data = data;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return temp;}Â
// Driver program to test above functionsint main(){    // Let us create binary tree shown in above diagram    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
// Iterative Queue based Java program// to do level order traversal// of Binary TreeÂ
import java.util.LinkedList;import java.util.Queue;Â
// Class to represent Tree nodeclass Node {Â Â Â Â int data;Â Â Â Â Node left, right;Â
    public Node(int item)    {        data = item;        left = null;        right = null;    }}Â
// Class to print Level Order Traversalclass BinaryTree {Â
    Node root;Â
    // Given a binary tree. Print    // its nodes in level order    // using array for implementing queue    void printLevelOrder()    {        Queue<Node> queue = new LinkedList<Node>();        queue.add(root);        while (!queue.isEmpty()) {Â
            // poll() removes the present head.             Node tempNode = queue.poll();            System.out.print(tempNode.data + " ");Â
            // Enqueue left child            if (tempNode.left != null) {                queue.add(tempNode.left);            }Â
            // Enqueue right child            if (tempNode.right != null) {                queue.add(tempNode.right);            }        }    }Â
    public static void main(String args[])    {        // Creating a binary tree and entering        // the nodes        BinaryTree tree_level = new BinaryTree();        tree_level.root = new Node(1);        tree_level.root.left = new Node(2);        tree_level.root.right = new Node(3);        tree_level.root.left.left = new Node(4);        tree_level.root.left.right = new Node(5);Â
        System.out.println("Level order traversal of binary tree is - ");        tree_level.printLevelOrder();    }} |
Python3
# Python program to print level# order traversal using QueueÂ
Â
# A node structureclass Node:Â
    # A utility function to create a new node    def __init__(self, key):        self.data = key        self.left = None        self.right = NoneÂ
Â
# Iterative Method to print the# height of a binary treedef printLevelOrder(root):Â
    # Base Case    if root is None:        returnÂ
    # Create an empty queue    # for level order traversal    queue = []Â
    # Enqueue Root and initialize height    queue.append(root)Â
    while(len(queue) > 0):Â
        # Print front of queue and        # remove it from queue        print(queue[0].data, end=" ")        node = queue.pop(0)Â
        # Enqueue left child        if node.left is not None:            queue.append(node.left)Â
        # Enqueue right child        if node.right is not None:            queue.append(node.right)Â
Â
# Driver Program to test above functionif __name__ == '__main__':Â Â Â Â 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)Â
Â
# This code is contributed by Nikhil Kumar Singh(nickzuck_007) |
C#
// Iterative Queue based C# program// to do level order traversal// of Binary TreeÂ
using System;using System.Collections.Generic;Â
// Class to represent Tree nodepublic class Node {Â Â Â Â public int data;Â Â Â Â public Node left, right;Â
    public Node(int item)    {        data = item;        left = null;        right = null;    }}Â
// Class to print Level Order Traversalpublic class BinaryTree {Â
    Node root;Â
    // Given a binary tree. Print    // its nodes in level order using    // array for implementing queue    void printLevelOrder()    {        Queue<Node> queue = new Queue<Node>();        queue.Enqueue(root);        while (queue.Count != 0) {Â
            Node tempNode = queue.Dequeue();            Console.Write(tempNode.data + " ");Â
            // Enqueue left child            if (tempNode.left != null) {                queue.Enqueue(tempNode.left);            }Â
            // Enqueue right child            if (tempNode.right != null) {                queue.Enqueue(tempNode.right);            }        }    }Â
    // Driver code    public static void Main()    {        // Creating a binary tree and entering        // the nodes        BinaryTree tree_level = new BinaryTree();        tree_level.root = new Node(1);        tree_level.root.left = new Node(2);        tree_level.root.right = new Node(3);        tree_level.root.left.left = new Node(4);        tree_level.root.left.right = new Node(5);Â
        Console.WriteLine("Level order traversal "                          + "of binary tree is - ");        tree_level.printLevelOrder();    }}Â
// This code contributed by PrinciRaj1992 |
Javascript
// Iterative Queue based javascript program// to do level order traversal// of Binary TreeÂ
// Class to represent Tree nodeclass Node {Â Â Â Â constructor(val) {Â Â Â Â Â Â Â Â this.data = val;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// Given a binary tree. Print its nodes // in level order using array for implementing queuefunction printLevelOrder() {    var queue = [];    queue.push(root);    while (queue.length != 0) {                     // The shift() method removes         // the first element from an array         // and returns that removed element.        var tempNode = queue.shift();        console.log(tempNode.data + " ");Â
        // Enqueue left child        if (tempNode.left != null) {            queue.push(tempNode.left);        }Â
        // Enqueue right child        if (tempNode.right != null) {            queue.push(tempNode.right);        }    }}Â
// creating a binary tree and entering the nodes    var 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);    console.log("Level order traversal of binary tree is - ");    printLevelOrder();Â
// This code is contributed by umadevi9616 |
Level Order traversal of binary tree is 1 2 3 4 5
Time Complexity: O(N) where N is the number of nodes in the binary tree.
Auxiliary Space: O(N) where N is the number of nodes in the binary tree.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

