描述
给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受
思路
无需思路,乱杀
解答
# 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 root is None:
return []
all_level = [root, ]
ret = []
while all_level:
level_cnt = 0
level_total = 0
nxt_level = []
for node in all_level:
if node:
level_cnt+=1
level_total+=node.val
node.left and nxt_level.append(node.left) or None
node.right and nxt_level.append(node.right) or None
if level_cnt > 0:
ret.append(level_total/level_cnt)
else:
ret.append(None)
all_level = nxt_level
return ret