Level order traversal
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Level order traversal visits tree nodes horizontal layer by horizontal layer using a Breadth-First Search queue.
Breadth-First Search with a FIFO Queue
Level order traversal visits a tree level by level from the top, left to right, using a queue. It is breadth-first search on a tree.
Depth-First Search explores deeply down individual paths before backtracking. In contrast, Breadth-First Search visits all nodes at the current depth before moving deeper. This layer-by-layer exploration is called level order traversal. Because nodes must be processed in the exact order they are discovered, we use a FIFO queue.
The algorithm begins by offering the root node into the queue. In each iteration, we poll the node at the front of the queue and process it. Then, we offer its left child and right child into the queue. The queue naturally preserves horizontal level order from left to right.
Trace level order on tree with root 1, left 2, right 3, left-left 4, left-right 5: Enqueue 1. Queue: [1]. Poll 1, enqueue 2 and 3. Queue: [2, 3]. Poll 2, enqueue 4 and 5. Queue: [3, 4, 5]. Poll 3 with no children. Queue: [4, 5]. Poll 4 and 5. Final sequence is 1 2 3 4 5.
Level order with a queue
Step 1 of 6
- 3
Collecting Levels and Zigzag Traversal
Record queue.size() before each level, then poll exactly that many nodes. Children added meanwhile belong to the next level.
Example 1 · Standard Level Order Traversal
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
public class LevelOrderDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new ArrayDeque<>(); queue.offer(root);
while (!queue.isEmpty()) { int levelSize = queue.size(); List<Integer> currentLevel = new ArrayList<>(); for (int i = 0; i < levelSize; i++) { TreeNode curr = queue.poll(); currentLevel.add(curr.val); if (curr.left != null) queue.offer(curr.left); if (curr.right != null) queue.offer(curr.right); } result.add(currentLevel); } return result; }
public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7);
System.out.println("Levels: " + levelOrder(root)); }}Levels: [[3], [9, 20], [15, 7]]
What this code does
- Captures queue.size() at each round to process exactly one level per iteration.
- Groups nodes into sublists by depth and enqueues children for the next level.
Example 2 · Zigzag Level Order Traversal
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Queue;
public class ZigzagDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); boolean leftToRight = true;
while (!queue.isEmpty()) { int size = queue.size(); List<Integer> level = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode curr = queue.poll(); level.add(curr.val); if (curr.left != null) queue.offer(curr.left); if (curr.right != null) queue.offer(curr.right); } if (!leftToRight) Collections.reverse(level); result.add(level); leftToRight = !leftToRight; } return result; }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.right.right = new TreeNode(5);
System.out.println("Zigzag: " + zigzagLevelOrder(root)); }}Zigzag: [[1], [3, 2], [4, 5]]
What this code does
- Toggles a boolean flag on every round to alternate collection direction.
- Reverses the current level list when travelling right to left.
Many problems require grouping nodes by their respective depth levels. To separate levels, we record queue.size() at the start of each level loop. A nested for-loop polls exactly that number of nodes for the current level. Any children offered during the loop belong strictly to the subsequent level.
This snapshot pattern enables collecting nodes into a List<List<Integer>>. It also enables computing level averages and finding the widest level in a tree. We can invert alternating levels to produce zigzag traversal. Odd levels collect left-to-right, while even levels collect right-to-left. Trace zigzag traversal on a tree with three levels. Level 0 reads left to right: [1]. Level 1 reads right to left: [3, 2]. Level 2 reads left to right: [4, 5, 6, 7]. Result is [[1], [3, 2], [4, 5, 6, 7]].
Find the bug
Find the level-order bug
Select the line that is wrong.
Each inner list should hold only one level.
Round 1 of 3Tree Views: Right Side and Left Side View
The right side view is the last node polled in each level. The left side view is the first node polled in each level.
Example 3 · Binary Tree Right Side View
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
public class RightSideViewDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new ArrayDeque<>(); queue.offer(root);
while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode curr = queue.poll(); if (i == size - 1) result.add(curr.val); if (curr.left != null) queue.offer(curr.left); if (curr.right != null) queue.offer(curr.right); } } return result; }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.right = new TreeNode(5); root.right.right = new TreeNode(4);
System.out.println("Right side view: " + rightSideView(root)); }}Right side view: [1, 3, 4]
What this code does
- Inspects loop index i to identify the final element at each depth level.
- Captures the rightmost visible node at each depth in linear time.
Level order traversal provides an intuitive way to compute tree side views. The right side view consists of the nodes you would see standing to the right of the tree. In each horizontal level, only the rightmost node is visible from that vantage point. When using the level snapshot loop, the last node polled in each level is the rightmost node.
Similarly, the left side view captures the first node polled in each level. Both view problems are solved by level order traversal in linear O(n) time. Space complexity is bounded by the maximum number of nodes in any single level. In a complete binary tree, the bottom level holds up to n / 2 nodes. Therefore, BFS queue space complexity is O(w), where w is the maximum tree width. In the worst case, this requires O(n) auxiliary queue memory. However, for balanced trees, queue memory is well within normal JVM limits. Level order BFS is one of the most versatile tools in tree problem solving.
Next step
Check your understanding
10 quick questions