Find Largest Value in Tree Row

Medium Topics Company Tags

Return an array containing the largest node value at each depth of the binary tree, ordered from the root downward. The root is at depth 0, its children are at depth 1, and so on. Return an empty array for an empty tree.

Compare all present nodes at the same depth, even when they have different parents. Missing children are not values and do not participate in the maximum.

Examples use level-order arrays. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted. [] represents an empty tree.

Example 1:

Find Largest Value in Each Tree Row, example 1: illustration of the example

Input: root = [5,9,-2,1,null,7,3]

Output: [5,9,7]

Explanation: The rows contain [5], [9,-2], and [1,7,3]. Their largest values are 5, 9, and 7, respectively.

Example 2:

Find Largest Value in Each Tree Row, example 2: illustration of the example

Input: root = [-5,-9,-6]

Output: [-5,-6]

Explanation: The root row has maximum -5. The next row contains -9 and -6, so its maximum is -6. Missing nodes do not contribute zero.

Example 3:

Find Largest Value in Each Tree Row, example 3: illustration of the example

Input: root = []

Output: []

Explanation: An empty tree has no rows, so the result is an empty array.

Constraints:

  • The tree contains between 0 and 10000 nodes.
  • -2147483648 <= Node.val <= 2147483647


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.