Design Gurus Logo
Maximum Level Sum of a Binary Tree (medium)

Problem Statement

Given a root of the binary tree, return the smallest level x, such that sum of all node's values at level x has maximum sum.

The level of a binary tree starts at 1 for the root node, and increases by 1 for each subsequent depth.

Examples

Example 1:

  • Input: [3,9,20,null,null,15,7]
Image
  • Expected Output: 2
  • Justification: The sum of each level is: Level 1: 3, Level 2: 29, Level 3: 22. The second level has the maximum sum, so the output is 2.

Example 2:

  • Input: [1,2,3,4,5,null,7]
Image
  • Expected Output: 3
  • Justification: The sums are Level 1: 1, Level 2: 5, Level 3: 16. The third level has the highest sum, thus the output is 3.

Example 3:

  • Input: [-10,20,null,15,25]
Image
  • Expected Output: 3
  • Justification: The sums are Level 1: -10, Level 2: 20, Level 3: 40. The third level's sum is the highest, making the output 3.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory