Problem 515 · LeetCode 515(opens in a new tab)
Find Largest Value in Each Tree Row
MediumBreadth-first search
You are given the root of a binary tree. Think of the tree as rows: the root is row 0, its children form row 1, their children form row 2, and so on.
Return a list holding the biggest node value in each row, from the top row down. An empty tree has no rows, so its answer is an empty list.
Example 1
Input: root = [5, 2, 9, 1, null, 7, 4] Output: [5, 9, 7] Why: rows are [5], [2, 9] and [1, 7, 4]
2 more examples and the constraints
Example 2
Input: root = [-6, -8, -3] Output: [-6, -3] Why: -3 beats -8 in the second row
Example 3
Input: root = [] Output: [] Why: no nodes, so no rows
Constraints
- The tree has between 0 and 10,000 nodes
- Each node value is a 32-bit signed integer, from −2,147,483,648 to 2,147,483,647
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS with a best per depthO(n)
- BFS, one row at a timeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| DFS with a best per depth | O(n) | Passes; deep trees need a big stack | |
| BFS, one row at a time | O(n) | Best; rows come for free |
n = number of nodes, h = tree height, w = widest row. Both touch every node once.
Edge cases to test
- Empty tree. [] has no rows, so return [].
- All negative. [-6, -8, -3] gives [-6, -3]; a best that starts at 0 would be wrong.
- Smallest integer. A row made only of −2,147,483,648 must return that value.
- A chain. [1, 2, null, 3] has one node per row, so each row best is that node.
Common mistakes
- Starting each row best at 0, which breaks rows of negative numbers.
- Reading the queue size inside the loop instead of once per row, so the next row leaks in.
- Forgetting the empty tree and pushing a null root into the queue.
How to talk through it
- 1Clarify. Can the tree be empty? Can values be negative or hit the integer limits?
- 2Name the traversal. One answer per row means level-order traversal, so BFS.
- 3Explain the size trick. At the start of each round, the queue holds exactly one row; record its size before popping.
- 4Code it. Start each row best at the smallest integer, and say why not 0.
- 5Test out loud. Run the empty tree, an all-negative tree and a chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?