Coding Interview PatternsFind Largest Value in Each Tree Row
MediumTree Breadth-First Search
Find Largest Value in Each Tree Row
Explanation & Solution
Description
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Examples
Example 1:
```tree
[1, 3, 2, 5, 3, null, 9]
`
Input:root = [1, 3, 2, 5, 3, null, 9]
0
1
1
3
2
2
3
5
4
3
5
null
6
9
Output:[1, 3, 9]
0
1
1
3
2
9
Explanation:
- Row 0: max(1) = 1
- Row 1: max(3, 2) = 3
- Row 2: max(5, 3, 9) = 9
Example 2:
```tree
[1, 2, 3]
`
Input:root = [1, 2, 3]
0
1
1
2
2
3
Output:[1, 3]
0
1
1
3
Example 3:
Input: root = []
Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 10⁴] -2³¹ <= Node.val <= 2³¹ - 1
Approach
Tree Breadth-First Search pattern
1. Handle Empty Tree
- If
rootisnull, return an empty array[]
2. Initialize BFS
- Create a
resultarray to hold the largest value per row - Create a
queueinitialized with the root node - Use a
headpointer for efficient dequeuing
3. Process Level by Level
- While there are nodes in the queue:
- Calculate
levelSize— the number of nodes at the current level - Initialize
maxto-Infinity - For each node in the current level:
- Update
maxif the node's value is larger - Enqueue left and right children if they exist
- Push
maxintoresult
4. Return Result
- After BFS completes,
resultcontains the largest value from each row - Return
result
Key Insight
- BFS naturally groups nodes by level, making it straightforward to find the maximum per level
- We simply track the running maximum while processing each level
Time
O(n)every node is visited exactly onceSpace
O(n)the queue may hold up to an entire level of nodesVisualization
Input:
DFS Traversal[1, 3, 2, 5, 3, 9]
output0
Press play to start DFS traversal
CurrentIn stackComplete
13 steps