# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
res = []
q = deque([root])
while q:
curr_sum = 0
node_num_this_layer = len(q)
for i in range(0, node_num_this_layer):
node = q.popleft();
curr_sum += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(1.0*curr_sum/node_num_this_layer)
return res
原文地址:https://www.cnblogs.com/theodoric008/p/9388281.html
时间: 2024-10-08 00:49:55