File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/average-of-levels-in-binary-tree/
2
+ # 637. Average of Levels in Binary Tree
3
+
4
+ from typing import Optional , List
5
+ from common .leetcodeds import TreeNode
6
+ from collections import deque , defaultdict
7
+
8
+
9
+ class Solution :
10
+ def averageOfLevels (self , root : Optional [TreeNode ]) -> List [float ]:
11
+ queue = deque ()
12
+ queue .append ((0 , root ))
13
+ result = []
14
+ count = defaultdict (int )
15
+
16
+ while queue :
17
+ depth , node = queue .popleft ()
18
+ if depth >= len (result ):
19
+ result .append (node .val )
20
+ else :
21
+ result [depth ] += node .val
22
+
23
+ count [depth ] += 1
24
+
25
+ if node .left is not None :
26
+ queue .append ((depth + 1 , node .left ))
27
+ if node .right is not None :
28
+ queue .append ((depth + 1 , node .right ))
29
+
30
+ for idx in range (len (result )):
31
+ result [idx ] /= count [idx ]
32
+
33
+ return result
You can’t perform that action at this time.
0 commit comments