Skip to content

Commit 10320fc

Browse files
committed
Maximum Level Sum of a Binary Tree
1 parent d68bd9d commit 10320fc

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
3+
4+
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
5+
Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
6+
7+
Example 1:
8+
Input: [1,7,0,7,-8,null,null]
9+
Output: 2
10+
Explanation:
11+
Level 1 sum = 1.
12+
Level 2 sum = 7 + 0 = 7.
13+
Level 3 sum = 7 + -8 = -1.
14+
So we return the level with the maximum sum which is level 2.
15+
16+
Note:
17+
The number of nodes in the given tree is between 1 and 10^4.
18+
-10^5 <= node.val <= 10^5
19+
"""
20+
# Definition for a binary tree node.
21+
# class TreeNode:
22+
# def __init__(self, x):
23+
# self.val = x
24+
# self.left = None
25+
# self.right = None
26+
27+
class Solution:
28+
def maxLevelSum(self, root: TreeNode) -> int:
29+
level = maxLevel = 0
30+
if not root:
31+
return maxLevel
32+
queue = [[root]]
33+
maxSum = float('-inf')
34+
while queue:
35+
level += 1
36+
levelNodes = queue.pop(0)
37+
nextLevel = []
38+
levelSum = 0
39+
while levelNodes:
40+
node = levelNodes.pop()
41+
levelSum +=node.val
42+
if node.left:
43+
nextLevel.append(node.left)
44+
if node.right:
45+
nextLevel.append(node.right)
46+
if nextLevel:
47+
queue.append(nextLevel)
48+
if levelSum > maxSum:
49+
maxSum = levelSum
50+
maxLevel = level
51+
return maxLevel

0 commit comments

Comments
 (0)