Level Order Traversal is an important tree traversal technique used in Data Structures and Algorithms (DSA). It visits the nodes of a tree level by level, starting from the root node and moving from left to right at each level. Level order traversal is a type of Breadth First Search (BFS) and uses a queue data structure to maintain the order in which nodes are processed. It is commonly used in binary trees, tree searching, finding the maximum width of a tree, and processing nodes according to their depth. Understanding this technique helps beginners learn tree operations and prepare for coding interviews.
Table of Contents
What Is Level Order Traversal?
Level Order Traversal is a tree traversal technique in which nodes are visited one level at a time, starting from the root node. It follows the Breadth-First Search (BFS) approach.
In this technique:
- First, visit the root node.
- Next, visit all nodes at the second level.
- Then, visit all nodes at the third level.
- Continue until every node has been visited.
Level order traversal processes nodes from left to right at each level in a binary tree.
Unlike Depth First Search (DFS), which explores one branch deeply before moving to another, BFS visits all nodes at the current level before moving to the next level.
How Does Level Order Traversal Work?
Level order traversal uses a queue to process nodes in the order they are discovered. A queue follows the First In, First Out (FIFO) principle. This means the node inserted first is removed and processed first.
The traversal starts by inserting the root node into the queue. The algorithm then removes the first node, visits it, and inserts its existing children into the queue.
This process continues until the queue becomes empty.
Important Points:
- A queue is used to maintain the visiting order.
- The root node is always processed first.
- Left and right children are inserted into the queue in that order.
- Every node is visited exactly once.
Steps of Level Order Traversal
The following steps explain how to perform level order traversal:
- Start from the root node.
- Check whether the root is null.
- Create an empty queue.
- Insert the root node into the queue.
- Remove the first node from the queue.
- Visit and process the removed node.
- Insert its left child into the queue if it exists.
- Insert its right child into the queue if it exists.
- Repeat until the queue becomes empty.
These steps ensure that all nodes are visited level by level.
Level Order Traversal Example
Consider a binary tree containing the following values:
- Root node: 10
- Left child: 20
- Right child: 30
- Children of node 20: 40 and 50
- Children of node 30: 60 and 70
Applying level-order traversal visits nodes level by level.
The visiting sequence is: 10 → 20 → 30 → 40 → 50 → 60 → 70
Explanation:
- First, visit node 10 because it is the root.
- Next, visit nodes 20 and 30 at the second level.
- Finally, visit nodes 40, 50, 60, and 70 at the third level.
The final level order traversal sequence is:
10, 20, 30, 40, 50, 60, 70
Level Order Traversal Using JavaScript
JavaScript can be used to implement level order traversal with an array-based queue. The program starts by inserting the root node into the queue. It then processes each node and adds its children to the queue.
JavaScript Example:
// This program performs level order traversal of a binary tree.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function levelOrder(root) {
if (root === null) {
return;
}
const queue = [root];
let front = 0;
while (front < queue.length) {
const current = queue[front++];
console.log(current.value);
if (current.left !== null) {
queue.push(current.left);
}
if (current.right !== null) {
queue.push(current.right);
}
}
}
const root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
root.right.right = new Node(70);
levelOrder(root);
Output:
10
20
30
40
50
60
70
Explanation:
- The Node class creates individual tree nodes.
- Each node stores a value and references to its left and right children.
- The levelOrder() function checks whether the root is null.
- The queue initially contains the root node.
- The front variable tracks the next node to process.
- Each node is visited, and its existing children are added to the queue.
- The loop continues until all nodes have been processed.
Why Is a Queue Used?
A queue follows the FIFO principle. It ensures that nodes discovered at an earlier level are processed before nodes at the next level.
Level Order Traversal Using a Queue
A queue is the main data structure used in level order traversal. It maintains the order in which nodes are discovered and processed.
The basic queue operations used are:
- Enqueue: Adds a node to the rear of the queue.
- Dequeue: Removes a node from the front of the queue.
- Front: Identifies the next node to be processed.
- Empty Check: Determines whether there are any nodes left to process.
In JavaScript, an array can be used as a queue. However, repeatedly calling shift() can be inefficient for large trees because the remaining elements need to be moved.
Using a front index avoids this overhead.
JavaScript Example:
// This program demonstrates queue-based level order traversal.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function levelOrder(root) {
const queue = [];
let front = 0;
if (root === null) {
return;
}
queue.push(root);
while (front < queue.length) {
const node = queue[front];
front++;
console.log(node.value);
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
}
const root = new Node(5);
root.left = new Node(15);
root.right = new Node(25);
root.left.left = new Node(35);
root.left.right = new Node(45);
levelOrder(root);
Output:
5
15
25
35
45
Explanation: The queue initially contains node 5.
- Node 5 is removed and visited.
- Its children 15 and 25 are added to the queue.
- Node 15 is processed next, followed by node 25.
- The children 35 and 45 are then processed.
- The traversal ends when there are no more nodes to visit.
This approach maintains the correct level order without repeatedly removing the first array element.
Level Order Traversal by Levels
Sometimes, we need to display or process the nodes separately for each level rather than printing all values in one sequence. This can be achieved by storing the number of nodes currently present in the queue before processing each level.
Steps:
- Insert the root node into the queue.
- Record the current queue size.
- Process exactly that many nodes.
- Add their children to the queue.
- Store the processed values of the current level.
- Repeat until the queue becomes empty.
JavaScript Example:
// This program performs level order traversal and groups nodes by level.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function levelOrderByLevels(root) {
if (root === null) {
return [];
}
const queue = [root];
let front = 0;
const result = [];
while (front < queue.length) {
const levelSize = queue.length - front;
const currentLevel = [];
for (let i = 0; i < levelSize; i++) {
const node = queue[front++];
currentLevel.push(node.value);
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
result.push(currentLevel);
}
return result;
}
const root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
console.log(levelOrderByLevels(root));
Output:
[[10], [20, 30], [40, 50]]
Explanation:
The program stores the nodes of each level in a separate array.
- The first level contains node 10.
- The second level contains nodes 20 and 30.
- The third level contains nodes 40 and 50.
This approach is useful when a problem requires processing or displaying each tree level separately.
Level Order Traversal in a Binary Search Tree
Level order traversal can also be performed on a Binary Search Tree (BST).
A Binary Search Tree is a special binary tree in which smaller values are stored in the left subtree and larger values are stored in the right subtree, following its ordering rules.
Level order traversal does not follow the sorted order of BST values. Instead, it visits nodes according to their levels.
JavaScript Example:
// This program performs level order traversal of a Binary Search Tree.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function insert(root, value) {
if (root === null) {
return new Node(value);
}
if (value < root.value) {
root.left = insert(root.left, value);
} else if (value > root.value) {
root.right = insert(root.right, value);
}
return root;
}
function levelOrder(root) {
if (root === null) {
return;
}
const queue = [root];
let front = 0;
while (front < queue.length) {
const current = queue[front++];
console.log(current.value);
if (current.left !== null) {
queue.push(current.left);
}
if (current.right !== null) {
queue.push(current.right);
}
}
}
let root = null;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 70);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 60);
root = insert(root, 80);
levelOrder(root);
Output:
50
30
70
20
40
60
80
Explanation:
The traversal starts with the root node 50.
- First, it visits 50.
- Next, it visits its children 30 and 70.
- Finally, it visits the next-level nodes 20, 40, 60, and 80.
The output follows the level order rather than ascending sorted order.
Applications of Level Order Traversal
Level order traversal is useful in several computer science applications.
- Tree Searching: It can find a value by checking nodes level by level.
- Finding Tree Width: It helps determine the maximum number of nodes present at any level.
- Finding Minimum Depth: It can find the nearest leaf node by processing levels in order.
- Shortest Path Problems: BFS is used to find shortest paths in unweighted graphs.
- Tree Printing: It helps display nodes according to their levels.
- Binary Tree Analysis: It supports operations such as finding the number of nodes at each level.
- Network Broadcasting: BFS-based processing helps distribute information level by level in network structures.
Time and Space Complexity
Time and space complexity describe how efficiently an algorithm uses processing time and memory.
Let N represent the total number of nodes in the tree, and W represent the maximum number of nodes at any level.
| Complexity | Value |
|---|---|
| Time Complexity | O(N) |
| Auxiliary Space Complexity | O(W) |
| Worst-Case Space Complexity | O(N) |
Time Complexity: O(N)
Level order traversal visits every node exactly once. Therefore, the time complexity is O(N).
Space Complexity: O(W)
The queue stores nodes that are waiting to be processed. Its maximum size depends on the maximum width of the tree. In the worst case, a tree can have O(N) nodes at a single level, so the auxiliary space complexity can become O(N).
Advantages of Level Order Traversal
Some important advantages of level order traversal are:
- It is easy to understand and implement using a queue.
- It visits nodes level by level.
- It is useful for finding the minimum depth of a binary tree.
- It helps calculate the maximum width of a tree.
- It is useful for processing nodes according to their depth.
- It can be applied to both binary trees and general trees.
Common Mistakes to Avoid
- Using a Stack Instead of a Queue: BFS requires a queue to maintain level-by-level processing.
- Forgetting the Empty Tree Condition: Always handle cases where the root node is null.
- Adding Null Children: Insert only existing left and right children into the queue.
- Processing the Wrong Number of Nodes Per Level: When grouping nodes by levels, record the queue size before processing the current level.
- Ignoring Queue Performance: Repeatedly using JavaScript's shift() can add unnecessary overhead for large trees.
Frequently Asked Questions
1. What is level order traversal?
Level order traversal is a tree traversal technique that visits nodes level by level, starting from the root node.
2. Which algorithm is used for level order traversal?
Level order traversal uses the Breadth First Search (BFS) algorithm.
3. Which data structure is used in level order traversal?
A queue is used because it follows the First In, First Out (FIFO) principle.
4. What is the time complexity of level order traversal?
The time complexity is O(N), where N is the total number of nodes in the tree.
5. What is the difference between DFS and BFS?
DFS explores one branch deeply before moving to another branch, whereas BFS visits all nodes at the current level before moving to the next level.
0 Comments