Problem 446661 · easy · Phase 04 Non-Linear Data Structures

Largest Value on Each Level

binary trees · breadth-first search · aggregation

A warehouse stacks crates in a binary tree of shelves. Given the root, return a list with the largest value on each level, from the root's level down to the deepest level. Return [] for an empty tree.

Examples

      4
     / \
    2   9
   / \   \
  7   1   3

Input:  root = build_tree([4, 2, 9, 7, 1, None, 3])
Output: [4, 9, 7]
Explanation: level maxima are max(4), max(2, 9) and max(7, 1, 3).
Input:  root = build_tree([-1, -5, -2])
Output: [-1, -2]

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Group nodes by level with a queue
  • Reduce each level to a single number
  • Handle negative values and the empty tree
Starting Python…