给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3
/
9 20
/
15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
提示:
节点值的范围在32位有符号整数范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if root is None: return [] res=[] def add_to_res(level,node): if level>len(res)-1: res.append([]) res[level].append(node.val) if node.left: add_to_res(level+1,node.left) if node.right: add_to_res(level+1,node.right) add_to_res(0,root) return res def averageOfLevels(self, root: TreeNode) -> List[float]: num=self.levelOrder(root) return [sum(i)/len(i) for i in num]
# 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]: res=[] cur=[root] while len(cur)>0: next=[] res.append(sum([x.val for x in cur])/len(cur)) for node in cur: if node.left:next.append(node.left) if node.right:next.append(node.right) cur=next return res