-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAverage of Levels in Binary Tree.py
52 lines (42 loc) · 1.23 KB
/
Average of Levels in 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
from collections import deque
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Time: O(n)
Memory: O(log(n))
"""
def averageOfLevels(self, root: TreeNode) -> List[float]:
level = (root,)
while level:
yield sum(node.val for node in level) / len(level)
level = (
child
for node in level
for child in (node.left, node.right)
if child is not None
)
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def averageOfLevels(self, root: TreeNode) -> List[float]:
queue = deque([root])
averages = []
while queue:
level_sum = level_cnt = 0
for _ in range(len(queue)):
node = queue.popleft()
if node is not None:
level_sum += node.val
level_cnt += 1
queue.append(node.left)
queue.append(node.right)
if level_cnt:
averages.append(level_sum / level_cnt)
return averages