给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
提示:
节点值的范围在32位有符号整数范围内。
方法一:DFS
# 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 == None:
return []
sum_count = []
ans = []
preorder(root, 0, sum_count)
for item in sum_count:
ans.append(item[0]/item[1])
return ans
def preorder(root, depth, sum_count):
if root == None: return;
if depth >= len(sum_count): sum_count.append([0, 0])
sum_count[depth][0] += root.val
sum_count[depth][1] += 1
preorder(root.left, depth+1, sum_count)
preorder(root.right, depth+1, sum_count)
方法二:BFS
# 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 == None:
return []
ans = []
curr = []
next = []
curr.append(root)
while len(curr) != 0:
sum = 0
for node in curr:
sum += node.val
if node.left: next.append(node.left)
if node.right: next.append(node.right)
ans.append(sum/len(curr))
curr = next
next = []
return ans
网友评论