Binary Tree Level Order Traversal
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Binary Tree Level Order Traversal
BFS traversal.
Approach 1
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.
⏱ O(N)💾 O(H) (due to recursion stack where H is tree height)
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]] |
Approach 2
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.
⏱ O(N)💾 O(N)
Detailed Dry Run
| Stack | Depth | res state |
|---|---|---|
| [(3,0)] | 0 | [[3]] |
| [(20,1), (9,1)] | 1 | [[3], [9]] |
| [(20,1)] | 1 | [[3], [9, 20]] |
Approach 3
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]⏱ O(N) (each node visited once)💾 O(N) (queue stores maximum level width)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.