Skip to content

Commit 1dae907

Browse files
1161. Maximum Level Sum of a Binary Tree
Difficulty: Medium 34 / 34 test cases passed. Runtime: 316 ms Memory Usage: 18 MB
1 parent 921fc3a commit 1dae907

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Given the root of a binary tree, the level of its root is 1, the level of
3+
its children is 2, and so on.
4+
Return the smallest level X such that the sum of all the values of nodes at
5+
level X is maximal.
6+
7+
Example:
8+
1
9+
/ \
10+
7 0
11+
/ \
12+
7 -8
13+
14+
Input: [1,7,0,7,-8,null,null]
15+
Output: 2
16+
Explanation:
17+
Level 1 sum = 1.
18+
Level 2 sum = 7 + 0 = 7.
19+
Level 3 sum = 7 + -8 = -1.
20+
So we return the level with the maximum sum which is level 2.
21+
22+
Note:
23+
1. The number of nodes in the given tree is between 1 and 10^4.
24+
2. -10^5 <= node.val <= 10^5
25+
"""
26+
#Difficulty: Medium
27+
#34 / 34 test cases passed.
28+
#Runtime: 316 ms
29+
#Memory Usage: 18 MB
30+
31+
#Runtime: 316 ms, faster than 89.30% of Python3 online submissions for Maximum Level Sum of a Binary Tree.
32+
#Memory Usage: 18 MB, less than 69.43% of Python3 online submissions for Maximum Level Sum of a Binary Tree.
33+
34+
# Definition for a binary tree node.
35+
# class TreeNode:
36+
# def __init__(self, val=0, left=None, right=None):
37+
# self.val = val
38+
# self.left = left
39+
# self.right = right
40+
41+
class Solution:
42+
def maxLevelSum(self, root: TreeNode) -> int:
43+
queue = [root]
44+
depth = 0
45+
level = 0
46+
summ = 0
47+
while queue:
48+
length = len(queue)
49+
level_sum = 0
50+
depth += 1
51+
while length:
52+
length -= 1
53+
node = queue.pop(0)
54+
level_sum += node.val
55+
if node.left:
56+
queue.append(node.left)
57+
if node.right:
58+
queue.append(node.right)
59+
if level_sum > summ:
60+
summ = level_sum
61+
level = depth
62+
return level

0 commit comments

Comments
 (0)