Maximum Level Sum of a Binary Tree Problem
Description
LeetCode Problem 1161.
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Example 1:
Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Example 2:
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. -10^5 <= Node.val <= 10^5
Solution
Approach: Level-Order Traversal (BFS)
We need the sum of every level, so we visit the tree level by level with a queue. At the start of each round the queue holds exactly the nodes of the current level. We take them all out, add up their values, and put their children in the queue: those are the next level.
We keep the best sum seen so far and its level, and update them only when a level's sum is strictly larger. That way, when two levels tie, the earlier (smaller) level stays the answer, as the problem asks.
Node values can be negative, so the best sum must start below any possible level sum (negative infinity, or the smallest integer), not at 0; otherwise a tree whose levels all have negative sums would never update the answer.
Complexity: O(n) time and O(n) space for the queue, where n is the number of nodes.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
q = deque([root])
best_sum, ans, level = float("-inf"), 0, 0
while q:
level += 1
s = 0
for _ in range(len(q)): # exactly the nodes of this level
node = q.popleft()
s += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if s > best_sum: # strictly greater, so ties keep the smaller level
best_sum, ans = s, level
return ans