-
Notifications
You must be signed in to change notification settings - Fork 0
/
avg-levels-bin-tree.py
41 lines (34 loc) · 1.17 KB
/
avg-levels-bin-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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
def bfs(root):
from collections import deque
queue = deque()
queue.append(root)
levels = [[root.val]]
while queue:
thatlevel=[]
node = queue.popleft()
# print(node.val)
if node.left:
queue.append(node.left)
thatlevel.append(node.left.val)
if node.right:
queue.append(node.right)
thatlevel.append(node.right.val)
levels.append(thatlevel)
return levels
if root is None:
return []
levels = bfs(root)
print(levels)
avgs = []
for level in levels:
if level:
avgs.append(sum(level)/len(level))
return avgs