Problem 467670 · medium · Phase 04 Non-Linear Data Structures

Level With the Largest Sum

binary trees · breadth-first search · aggregation

Levels are numbered from 1 at the root. Given the root of a binary tree, return the smallest level number whose node values have the largest total. Return 0 for an empty tree.

Examples

     1
    / \
   7   0
  / \
 7  -8

Input:  root = build_tree([1, 7, 0, 7, -8])
Output: 2
Explanation: level sums are 1, 7 and -1; level 2 wins.
Input:  root = build_tree([-5, -3, -4])
Output: 1
Explanation: -5 beats -7.

Constraints

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

Goals

  • Sum the values of each level during BFS
  • Track the best level and break ties toward the smaller level number
  • Handle negative values (the best sum can be negative)
Starting Python…