leetcode-637-Average-of-Levels-in-Binary-Tree

描述


Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

1
2
3
4
5
6
7
8
9
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node’s value is in the range of 32-bit signed integer.

分析


层级遍历一颗二叉树可以用深度优先遍历方法或宽度优先遍历的方法,这两种方法都需要额外的空间复杂度。深度优先遍历一般需要数组或 Map,宽度优先遍历一般需要队列。这道题是一道比较简单,典型的题目。

解决方案1(Java)


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
32
33
34
35
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Integer> count = new ArrayList<>();
List<Double> result = new ArrayList<>();
DFS(root, 0, result, count);
for (int i = 0; i < result.size(); i++) {
result.set(i, result.get(i)/count.get(i));
}
return result;
}

private void DFS(TreeNode node, int i, List<Double> sum, List<Integer> count) {
if (node == null) {
return;
}
if (i == sum.size()) {
sum.add(1.0*node.val);
count.add(1);
} else {
sum.set(i, sum.get(i)+node.val);
count.set(i, count.get(i)+1);
}
DFS(node.left, i+1, sum, count);
DFS(node.right, i+1, sum, count);
}
}

相关问题


题目来源