Leetcode 637.二叉树的层平均值

637. 二叉树的层平均值

题目

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

1
2
3
4
5
6
7
8
9
10
11
示例 1:

输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].

注意:

节点值的范围在32位有符号整数范围内。

方法1:宽度优先遍历

  • 当前根节点进队
  • 初始化sum和count为0,temp为空队列
  • 弹出队列的首元素(出队),增加出队元素的值到该层的sum,并更新该层的count
  • 将出队结点的左右子节点进队到temp临时队列(不是queue队列)
  • 重复步骤3和4直至对立queue为空
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
return []

queue=collections.deque([(root)])
avg=[]
while queue:
level_avg=[]
for i in range(len(queue)):
node=queue.popleft()
level_avg.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
avg.append(sum(level_avg)*1.0/len(level_avg))
return avg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
return []

queue=collections.deque([(root)])
avg=[]
while queue:
level_avg=[]
q=collections.deque()
while queue:
node=queue.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level_avg.append(node.val)
avg.append(sum(level_avg)*1.0/len(level_avg))
queue=q
return avg

方法2:深度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
d=collections.defaultdict(list)
def dfs(node,depth):
if node:
d[depth].append(node.val)
dfs(node.left,depth+1)
dfs(node.right,depth+1)
dfs(root,0)
return list(map(lambda x:sum(x)*1.0/len(x),d.values()))