637. 二叉树的层平均值
image.png
思路
继续采用广度优先遍历的方式,只需要稍微调整一下代码即可。可以参考:
# 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]: if root is None: return [] ans = [] queue = [root] while len(queue) > 0: size = len(queue) # 记录这一层的总数 total = 0 for _ in range(size): current = queue.pop(0) total += current.val if current.left is not None: queue.append(current.left) if current.right is not None: queue.append(current.right) # ans数组添加进去平均值,不用担心size为0的问题,因为size肯定>0 # 因为queue后面的出队和入队已经不影响size了 ans.append(total / size) return ans
image.png