393. Find Largest Value in Each Tree Row
You are given the root of a binary tree. Number the rows by depth: the root sits in row 0, its children in row 1, and so on.
For every row, find the largest node value in that row, and return those maximums as an array ordered from the top row down. An empty tree yields an empty array.
Node values can be negative, so a row's maximum is not necessarily positive.
Example 1:
Input: root = [4, 2, 7, 1, 3, null, 9]
Output: [4, 7, 9]
Explanation: Row 0 holds only 4. Row 1 holds 2 and 7, and 7 is larger. Row 2 holds 1, 3 and 9, and 9 wins.
Example 2:
Input: root = [-1, -5, -2]
Output: [-1, -2]
Explanation: Row 1 contains -5 and -2; the larger is -2. All-negative rows are why you cannot seed a row's maximum with 0.
Constraints:
- 0 ≤ number of nodes ≤ 10⁴
- -2³¹ ≤ Node.val ≤ 2³¹ - 1
Hints:
Each row is exactly one level of the tree. Which traversal visits nodes one full level at a time?
BFS with a queue: snapshot the queue's length, pop exactly that many nodes (one whole row) while tracking the max, then repeat. A DFS that carries the current depth and updates ans[depth] works too.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: root = [4, 2, 7, 1, 3, null, 9]
Expected output: [4, 7, 9]