LeetCode 637 Average of Levels in Binary Tree

题意

给予一颗二叉树,返回其每层节点的平均值.

例 :

1
2
3
4
5
6
7
给予树:
3
/ \
9 20
/ \
15 7
返回: [3, 14.5, 11]

解法

采用广度优先遍历, 遍历每一行的数据, 相加并除以每一层的个数即可.

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
36
37
38
39
/**
* 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<Double> result = new ArrayList<>();

if (root == null) {
return result;
}

Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
double sum = 0;
for (int i = 0; i < size; i++) {
TreeNode node = queue.remove();
sum += node.val;

if (node.left != null) {
queue.add(node.left);
}

if (node.right != null) {
queue.add(node.right);
}
}
result.add(sum / size);
}
return result;
}
}

Runtime: 2 ms, faster than 99.14% of Java online submissions for Average of Levels in Binary Tree.
Memory Usage: 39.2 MB, less than 99.96% of Java online submissions for Average of Levels in Binary Tree.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-637/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!