Maximum Level Sum of a Binary Tree LeetCode solution in Python

1
class Solution:
2
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
3
global_max = float("-inf")
4
res = -1
5
q = deque([root])
6
lvl = 1
7
while q:
8
total = 0
9
for _ in range(len(q)):
10
node = q.popleft()
11
if node.left:
12
q.append(node.left)
13
if node.right:
14
q.append(node.right)
15
total += node.val
16
if total > global_max:
17
res = lvl
18
global_max = total
19
lvl += 1
20
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0