FastPrepMaximum Value at Each Tree Level

Maximum Value at Each Tree Level

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree, return the maximum node value at every level, ordered from the root level downward.

Nodes are on the same level when they have the same number of edges from the root. Return exactly one maximum for each existing level, including repeated maximum values. For an empty tree, return an empty array.

The input uses level-order tree notation with null for a missing child. The function receives the constructed TreeNode root.

Function

largestValues(root: TreeNode) → int[]

Examples

Example 1

root = [1,3,2,5,3,null,9]return = [1,3,9]

The maximum values at depths zero, one and two are 1, 3 and 9.

Example 2

root = [1,2,3]return = [1,3]

The root level contributes 1, and the child level contributes 3.

Example 3

root = []return = []

An empty tree has no levels, so the result is empty.

Constraints

  • The tree contains between 0 and 10^3 nodes.
  • Node values are signed 32-bit integers and may repeat or be negative.
  • The input is a valid binary tree.

More Meta problems

See Meta hiring insights
public int[] largestValues(TreeNode root) {
    // Write your solution here.
}
root[1,3,2,5,3,null,9]
expected[1,3,9]
Checking account…