Skip to content

1116. Maximum Level Sum Of A Binary Tree

Tree Depth-First Search Breadth-First Search Binary Tree

Problem - Maximum Level Sum Of A Binary Tree

Medium

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, 104].
  • -105 <= Node.val <= 105

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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
class Solution:
    def maxLevelSum(self, root: Optional[TreeNode]) -> int:
        # val_set = defaultdict(int)

        # def dfs(root: Optional[TreeNode], level: int):
        #     if root is None:
        #         return
        #     dfs(root.left, level + 1)
        #     val_set[level] += root.val
        #     dfs(root.right, level + 1)
        #     return

        # dfs(root, 1)
        # print(val_set)

        # sum_val = float('-inf')
        # result = 1
        # for i, val in val_set.items():
        #     if val > sum_val or (val == sum_val and i < result):
        #         result = i
        #         sum_val = val
        # return result

        curr_level = min_level = 1
        max_sum = float('-inf')
        queue = deque()
        queue.append(root)

        while queue:
            curr_sum = 0
            for _ in range(len(queue)):
                curr = queue.popleft()
                curr_sum += curr.val
                if curr.left:
                    queue.append(curr.left)
                if curr.right:
                    queue.append(curr.right)

            if curr_sum > max_sum:
                max_sum = curr_sum
                min_level = curr_level
            curr_level += 1

        return min_level

Submission Stats:

  • Runtime: 12 ms (89.93%)
  • Memory: 21.5 MB (94.62%)