给定一个非空二叉树的根节点 root
, 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5
以内的答案可以被接受。
# @lc app=leetcode.cn id=637 lang=python3
#
# [637] 二叉树的层平均值
#
# @lc code=start
# 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: Optional[TreeNode]) -> List[float]:
if not root: return [] #注意特殊情况:树为空返回[]
queue = [root]
list1 = []
while queue:
list2 = 0
lens=len(queue)
for i in range(lens):
a = queue.pop(0)#元素出队列
if a.left :
queue.append(a.left)
if a.right:
queue.append(a.right)
list2=list2+a.val
list1.append(list2/lens)
return list1
# @lc code=end
