LeetCode 637 Average of Levels in Binary Tree 解题报告
题目要求
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
题目分析及思路
给定一棵非空二叉树,要求以列表的形式返回每一层结点值的平均值。可以使用队列保存结点,进行层次遍历,要特别注意空结点的判断。
python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
aves = []
q = collections.deque()
q.append(root)
while q:
level = []
size = len(q)
count = 0
for _ in range(size):
node = q.popleft()
if not node:
count += 1
continue
level.append(node.val)
q.append(node.left)
q.append(node.right)
if size-count != 0:
aves.append(sum(level)/(size-count))
return aves