题目
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
解题思路
从根开始一层一层bfs,遍历的时候求出每层的平均值
代码
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
res = []
q = [root]
while q:
tmp = []
s = 0
for n in q:
s += n.val
if n.left:
tmp.append(n.left)
if n.right:
tmp.append(n.right)
res.append(s / len(q))
q = tmp
return res