allizwell.jobsdoor360.in

Level Order Traversal

Data Structures and Algorithms / Trees and Binary Search Trees / Level Order Traversal

Level Order Traversal in Data Structures

Level Order Traversal is a tree traversal technique in which we visit all nodes level by level, starting from the root. First, we visit the root node, then all nodes at the second level from left to right, followed by the nodes at the next level. It is a Breadth First Search (BFS) technique and uses a Queue data structure to maintain the correct visiting order.

1. What Is Level Order Traversal?

Level Order Traversal visits the nodes of a Binary Tree according to their levels. Instead of going deep into one branch, it processes all nodes at the current level before moving to the next level.

Consider the following Binary Tree:

              1
             / \
            2   3
           / \ / \
          4  5 6  7

The nodes are visited in this order:

1 2 3 4 5 6 7

First, node 1 is visited. Then nodes 2 and 3 are visited. Finally, nodes 4, 5, 6, and 7 are visited.

Remember: Level Order Traversal visits nodes level by level, generally from left to right.

2. Why Do We Need Level Order Traversal?

Sometimes we need to process a tree according to its levels instead of following a depth-first path. Level Order Traversal makes this possible.

It is useful for:

  • Printing a tree level by level.
  • Finding the number of nodes at each level.
  • Finding the maximum width of a Binary Tree.
  • Finding the minimum depth of a tree.
  • Finding the leftmost or rightmost node at a level.
  • Solving shortest-path problems in unweighted graphs using BFS.
  • Building level-based views of a tree.

3. Level Order Traversal Uses BFS

BFS stands for Breadth First Search. It explores all nearby nodes first before moving farther away.

In a tree, BFS visits all nodes at one level before visiting nodes at the next level.

              1          Level 0
             / \
            2   3        Level 1
           / \ / \
          4  5 6  7      Level 2

The traversal proceeds as follows:

  1. Visit node 1 at Level 0.
  2. Visit nodes 2 and 3 at Level 1.
  3. Visit nodes 4, 5, 6, and 7 at Level 2.

4. Why Do We Use a Queue?

A Queue is a linear data structure that follows the First In, First Out (FIFO) principle.

This means the element inserted first is removed first. This behavior is exactly what we need for Level Order Traversal.

Queue Operations

  • push(): Inserts an element at the rear of the queue.
  • front(): Returns the element at the front.
  • pop(): Removes the front element.
  • empty(): Checks whether the queue is empty.
  • size(): Returns the number of elements in the queue.

Simple Queue Example

Suppose we insert 10, 20, and 30 into a queue.

Push 10
Push 20
Push 30

Queue: 10 20 30

Pop

Queue: 20 30

Since 10 was inserted first, it is removed first. The same principle is used in Level Order Traversal.

5. Algorithm for Level Order Traversal

We use a queue to store nodes that need to be processed. Initially, we insert the root node into the queue.

Step-by-Step Algorithm

  1. If the root is nullptr, return because the tree is empty.
  2. Create an empty queue of tree node pointers.
  3. Insert the root node into the queue.
  4. While the queue is not empty, take the front node.
  5. Remove that node from the queue.
  6. Process or print its data.
  7. If its left child exists, insert it into the queue.
  8. If its right child exists, insert it into the queue.
  9. Repeat until the queue becomes empty.
Important: Always insert the left child before the right child when you want the usual left-to-right Level Order Traversal.

6. Level Order Traversal Example

Consider this Binary Tree:

              1
             / \
            2   3
           / \ / \
          4  5 6  7

We will process this tree using a queue.

Initial Condition

Initially, insert the root node 1.

Queue: [1]

Output: Empty

Step 1

Remove node 1 from the queue and print it. Insert its left child 2 and right child 3.

Queue: [2, 3]

Output: 1

Step 2

Remove node 2 and print it. Insert its left child 4 and right child 5.

Queue: [3, 4, 5]

Output: 1 2

Step 3

Remove node 3 and print it. Insert its left child 6 and right child 7.

Queue: [4, 5, 6, 7]

Output: 1 2 3

Step 4

Remove node 4 and print it. It has no children, so nothing is inserted.

Queue: [5, 6, 7]

Output: 1 2 3 4

Step 5

Remove node 5 and print it. It has no children.

Queue: [6, 7]

Output: 1 2 3 4 5

Step 6

Remove node 6 and print it.

Queue: [7]

Output: 1 2 3 4 5 6

Step 7

Remove node 7 and print it.

Queue: []

Output: 1 2 3 4 5 6 7

Final Traversal Output

1 2 3 4 5 6 7

7. C++ Program for Level Order Traversal

Now let us implement Level Order Traversal using the queue provided by the C++ Standard Template Library.

C++ Code

#include <iostream>
#include <queue>
using namespace std;

struct Node {

    int data;
    Node* left;
    Node* right;

    Node(int value) {

        data = value;
        left = nullptr;
        right = nullptr;
    }
};

void levelOrder(Node* root) {

    if (root == nullptr) {
        return;
    }

    queue<Node*> q;

    // Insert root into queue
    q.push(root);

    while (!q.empty()) {

        // Get the front node
        Node* current = q.front();

        // Remove it from queue
        q.pop();

        // Print current node
        cout << current->data << " ";

        // Insert left child
        if (current->left != nullptr) {
            q.push(current->left);
        }

        // Insert right child
        if (current->right != nullptr) {
            q.push(current->right);
        }
    }
}

int main() {

    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->left = new Node(6);
    root->right->right = new Node(7);

    cout << "Level Order Traversal: ";

    levelOrder(root);

    return 0;
}

Output

Level Order Traversal: 1 2 3 4 5 6 7

Code Explanation

  1. Empty tree check: If root is nullptr, there is nothing to traverse.
  2. Queue creation: We create a queue that stores Node pointers.
  3. Insert root: The root is the first node to be processed.
  4. Process nodes: We remove the front node and print its value.
  5. Insert children: Its existing left and right children are added to the queue.
  6. Repeat: The loop continues until all nodes have been processed.

8. Level Order Traversal Level by Level

Sometimes we do not want a single sequence of values. Instead, we want to store or print the values of each level separately.

For example, the tree below has three levels:

              1
             / \
            2   3
           / \ / \
          4  5 6  7

The level-wise output is:

Level 0: 1

Level 1: 2 3

Level 2: 4 5 6 7

How Do We Separate Levels?

We can use the queue's size at the beginning of each iteration. That size tells us how many nodes belong to the current level.

We process exactly that many nodes before starting the next level.

C++ Code: Level-Wise Traversal

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

struct Node {

    int data;
    Node* left;
    Node* right;

    Node(int value) {

        data = value;
        left = nullptr;
        right = nullptr;
    }
};

vector<vector<int>> levelOrderByLevel(Node* root) {

    vector<vector<int>> result;

    if (root == nullptr) {
        return result;
    }

    queue<Node*> q;

    q.push(root);

    while (!q.empty()) {

        int levelSize = q.size();

        vector<int> currentLevel;

        for (int i = 0; i < levelSize; i++) {

            Node* current = q.front();
            q.pop();

            currentLevel.push_back(current->data);

            if (current->left != nullptr) {
                q.push(current->left);
            }

            if (current->right != nullptr) {
                q.push(current->right);
            }
        }

        result.push_back(currentLevel);
    }

    return result;
}

int main() {

    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->left = new Node(6);
    root->right->right = new Node(7);

    vector<vector<int>> result =
        levelOrderByLevel(root);

    for (int i = 0; i < result.size(); i++) {

        cout << "Level " << i << ": ";

        for (int value : result[i]) {
            cout << value << " ";
        }

        cout << endl;
    }

    return 0;
}

Output

Level 0: 1

Level 1: 2 3

Level 2: 4 5 6 7

Important Explanation: levelSize

The statement int levelSize = q.size(); stores the number of nodes currently waiting in the queue. These nodes belong to the current level.

The for loop processes exactly those nodes. Their children are added to the queue, but they are processed only in the next iteration of the outer while loop.

Interview Tip: Using the queue size at the beginning of each level is a common pattern for solving level-based Binary Tree problems.

9. Time and Space Complexity

Let N represent the total number of nodes in the Binary Tree.

Time Complexity

Every node is inserted into the queue once and removed from the queue once. Each node is also processed once.

Time Complexity = O(N)

Space Complexity

The queue stores nodes that are waiting to be processed. In a broad tree, the queue may contain many nodes from the same level.

If W is the maximum number of nodes present at any one level, the queue requires O(W) auxiliary space. In the worst case, W can be O(N).

Auxiliary Space = O(W), worst case O(N)

Operation Complexity
Insert a node into queue O(1)
Remove a node from queue O(1)
Visit all N nodes O(N)
Auxiliary queue space O(W), worst case O(N)

10. Difference Between DFS and BFS

DFS and BFS are two major ways to traverse a tree. They differ in how they explore nodes.

Feature DFS BFS
Full Form Depth First Search Breadth First Search
Traversal Style Explores deeply first Explores level by level
Common Data Structure Stack or recursion Queue
Tree Examples Preorder, Inorder, Postorder Level Order
Time Complexity O(N) O(N)

11. Important Applications of Level Order Traversal

1. Finding the Maximum Width of a Tree

The maximum width is the maximum number of nodes present at any single level. Level Order Traversal helps us count the nodes at each level.

2. Finding the Minimum Depth

The minimum depth is the shortest distance from the root to a leaf node. BFS can find the first leaf encountered, which gives the minimum depth.

3. Printing a Tree Level by Level

We can use the queue size to group nodes belonging to the same level and print them separately.

4. Finding the Right Side View

By processing each level and selecting its last node, we can find the right-side view of a Binary Tree.

5. Finding the Left Side View

By selecting the first node at each level, we can find the left-side view of a Binary Tree.

12. Common Mistakes Beginners Make

  • Using a stack instead of a queue for standard Level Order Traversal.
  • Forgetting to check whether the root is nullptr.
  • Removing a node from the queue before reading its value incorrectly.
  • Inserting the right child before the left child when left-to-right order is expected.
  • Forgetting to add existing children to the queue.
  • Confusing Level Order Traversal with Preorder traversal.
  • Forgetting to store the queue size when processing one level at a time.
  • Assuming the queue always stores only one level; it can contain nodes from more than one level while processing.

13. Important Interview Questions

Q1. What is Level Order Traversal?

Level Order Traversal is a technique that visits nodes level by level, starting from the root.

Q2. Which algorithm is used for Level Order Traversal?

Breadth First Search (BFS) is used for Level Order Traversal.

Q3. Which data structure is used in Level Order Traversal?

A Queue is used because it follows the First In, First Out principle.

Q4. What is the time complexity of Level Order Traversal?

O(N), because every node is processed exactly once.

Q5. What is the auxiliary space complexity?

O(W), where W is the maximum number of nodes at any level. The worst-case auxiliary space can be O(N).

Q6. What happens if the root is nullptr?

The traversal returns immediately because an empty tree has no nodes to visit.

Q7. What is the difference between BFS and DFS?

BFS visits nodes level by level using a queue, while DFS explores one branch deeply before moving to another branch.

Q8. How can we print nodes level by level separately?

Store the queue size at the beginning of each level and process exactly that many nodes before moving to the next level.

Q9. Can Level Order Traversal be performed recursively?

Yes, it is possible using recursion and the height of the tree, but the queue-based BFS approach is generally more direct and efficient for standard Level Order Traversal.

Q10. Is Level Order Traversal a DFS technique?

No. Level Order Traversal is a Breadth First Search (BFS) technique.

14. Practice Problems

  1. Implement Level Order Traversal using a queue in C++.
  2. Print all nodes of a Binary Tree level by level.
  3. Count the number of nodes at each level.
  4. Find the maximum width of a Binary Tree.
  5. Find the minimum depth of a Binary Tree using BFS.
  6. Find the left-side view of a Binary Tree.
  7. Find the right-side view of a Binary Tree.
  8. Print the nodes of each level on a separate line.
  9. Find the sum of nodes at every level.
  10. Return the level-wise traversal as a two-dimensional vector.

15. Summary

Level Order Traversal is a Breadth First Search technique that visits all nodes of a Binary Tree level by level. It uses a Queue to maintain the order in which nodes are processed.

  • Start by inserting the root into the queue.
  • Remove the front node and process it.
  • Insert its left child if it exists.
  • Insert its right child if it exists.
  • Continue until the queue becomes empty.

Its time complexity is O(N), and its auxiliary queue space is O(W), where W is the maximum width of the tree.

Key Takeaway: Remember that Level Order Traversal uses a Queue and follows the FIFO principle. It is the standard BFS technique for visiting a Binary Tree level by level.
Scroll to Top