Binary Tree Level Order Traversal
Master this topic with zero to advance depth.
Binary Tree Level Order Traversal
BFS traversal.
Level I: Recursive depth-first (DFS)
Intuition
We can use recursion to traverse the tree. By passing the current depth (level) as an argument, we can add each node's value to a list corresponding to its level. If the list for a level doesn't exist yet, we create it.
Thought Process
- Maintain a list of lists
res. - Call
helper(node, level). - If
res.size() == level, add a new inner list. res.get(level).add(node.val).- Recurse left and right with
level + 1.
Detailed Dry Run
| Node | Level | Result (State) |
|---|---|---|
| 3 | 0 | [[3]] |
| 9 | 1 | [[3], [9]] |
| 20 | 1 | [[3], [9, 20]] |
| 15 | 2 | [[3], [9, 20], [15]] |
Level II: Iterative DFS (using Stack)
Intuition
While BFS is the natural choice for level-order, we can simulate it using DFS with depth tracking. We maintain a stack of (node, depth). If the result list size is equal to the current depth, we add a new empty list. Then, we add the node value to the list corresponding to its depth.
Logic
- Use a Stack for DFS.
- Track
depthfor each node. res[depth].add(node.val).- Note: Push right child first, then left to maintain left-to-right order in levels.
Detailed Dry Run
| Stack | Depth | res state |
|---|---|---|
| [(3,0)] | 0 | [[3]] |
| [(20,1), (9,1)] | 1 | [[3], [9]] |
| [(20,1)] | 1 | [[3], [9, 20]] |
Level III: Optimal (BFS with Queue)
Intuition
Thought Process
The standard way to perform level-order traversal is Breadth-First Search (BFS) using a Queue. We process the tree level by level. For each level, we record how many nodes are currently in the queue; this count is the number of nodes in that specific level.
Diagram
Queue: [3] -> Level nodes: [3]
Queue: [9, 20] -> Level nodes: [9, 20]
Queue: [15, 7] -> Level nodes: [15, 7]Detailed Dry Run
| Queue | Level Size | Processing | Result Area |
|---|---|---|---|
| [3] | 1 | Pop 3, Push 9, 20 | [3] |
| [9, 20] | 2 | Pop 9, Pop 20, Push 15, 7 | [9, 20] |
| [15, 7] | 2 | Pop 15, Pop 7 | [15, 7] |
⚠️ Common Pitfalls & Tips
Empty tree checking is vital (if root == null). Forget this and the while loop might run on a null list or throw errors.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.