Return the maximum value found on each level of a binary tree.
Given the root of a binary tree, compute the largest node value present on every row of the tree, from top to bottom. The first row contains the root, the second row contains its children, and so on. Return the maximum value from each row in order.
You may solve this using either level-order traversal or a depth-first traversal that tracks the best value seen at each depth.
Input Format
- A binary tree root node.
- Each node contains an integer value and zero, one, or two children.
Output Format
- Return an array of integers where the -th value is the maximum node value on level of the tree.
Constraints
- The tree may be empty.
- Node values may be negative or positive integers.
- The number of nodes is finite.
Example 1
Input
root = [1,3,2,5,3,null,9]
Output
[1,3,9]
Explanation
Level 0 has [1], level 1 has [3,2], and level 2 has [5,3,9]. The largest values are 1, 3, and 9.
Example 2
Input
root = [1,2,3]
Output
[1,3]
Explanation
The first level contains 1, and the second level contains 2 and 3. The maximums are 1 and 3.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.