-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path637.py
58 lines (55 loc) · 1.82 KB
/
637.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
__________________________________________________________________________________________________
sample 44 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
return []
res = []
q = [root]
while q:
level_sum = 0
level_count = 0
next_level = []
for node in q:
level_sum += node.val
level_count += 1
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
q = next_level
res.append(level_sum/level_count)
return res
__________________________________________________________________________________________________
sample 15420 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
return []
stack = [root]
res = []
while stack:
current = []
next_level = []
for node in stack:
current.append(node)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
res.append(sum(i.val for i in current) / len(current))
stack = next_level
return res
__________________________________________________________________________________________________