本题注意点:二叉树的逐层遍历,孩子结点入队的同时统计该层孩子结点的总数n,然后出队时将n个结点出队。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
from collections import deque
ans = []
q = deque()
q.append(root)
n = 1
while(True):
cnt = 0
sum = 0
for i in range(n):
t = q.popleft()
sum += t.val
if t.left:
q.append(t.left)
cnt += 1
if t.right:
q.append(t.right)
cnt += 1
ans.append(float(sum)/n)
if cnt == 0: break
n = cnt
return ans