Coding Interview PatternsBinary Tree Level Order Traversal
MediumTree Breadth-First Search
Binary Tree Level Order Traversal
Explanation & Solution
Description
Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).
Examples
Example 1:
```tree
[3, 9, 20, null, null, 15, 7]
`
Input:root = [3, 9, 20, null, null, 15, 7]
0
3
1
9
2
20
3
null
4
null
5
15
6
7
Output: [[3], [9, 20], [15, 7]]
Example 2:
```tree
[1]
`
Input:root = [1]
0
1
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 2000] -1000 <= Node.val <= 1000
Approach
Tree Breadth-First Search pattern
1. Handle Empty Tree
- If
rootisnull: - Return
[] - Reason:
- No nodes means no levels to traverse
2. Initialize BFS
- Create
result = []to hold all levels - Create
queue = [root]to process nodes level by level - Create
head = 0as a pointer for efficient dequeue
3. Process Level by Level
- While
head < queue.length(queue is not empty): - Calculate
levelSize = queue.length - head - This captures exactly how many nodes are on the current level
4. Process Each Node in the Level
- Loop
levelSizetimes: - Dequeue node via
queue[head++] - Push
node.valinto the currentlevelarray - If
node.leftexists, enqueue it - If
node.rightexists, enqueue it
5. Collect the Level
- After processing all nodes in a level:
- Push the
levelarray intoresult
6. Return Result
- After all levels are processed, return
result - Each sub-array contains values from left to right for that level
Key Insight
- BFS naturally processes nodes level by level
- The trick is snapshotting
levelSizebefore adding children - Using a head pointer avoids costly
shift()operations — O(1) dequeue
Time
O(n)visit each node onceSpace
O(n)queue holds at most one level of nodesVisualization
Input:
DFS Traversal[3, 9, 20, 15, 7]
output0
Press play to start DFS traversal
CurrentIn stackComplete
11 steps