forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-level-sum-of-a-binary-tree.py
59 lines (51 loc) · 1.41 KB
/
maximum-level-sum-of-a-binary-tree.py
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
51
52
53
54
55
56
57
58
59
# Time: O(n)
# Space: O(h)
import collections
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# dfs solution
class Solution(object):
def maxLevelSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, i, level_sums):
if not node:
return
if i == len(level_sums):
level_sums.append(0)
level_sums[i] += node.val
dfs(node.left, i+1, level_sums)
dfs(node.right, i+1, level_sums)
level_sums = []
dfs(root, 0, level_sums)
return level_sums.index(max(level_sums))+1
# Time: O(n)
# Space: O(w)
# bfs solution
class Solution2(object):
def maxLevelSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result, level, max_total = 0, 1, float("-inf")
q = collections.deque([root])
while q:
total = 0
for _ in xrange(len(q)):
node = q.popleft()
total += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if total > max_total:
result, max_total = level, total
level += 1
return result