forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAverageOfLevelsInBinaryTree.java
46 lines (35 loc) · 1.02 KB
/
AverageOfLevelsInBinaryTree.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
36
37
38
39
40
41
42
43
44
45
46
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class AverageOfLevelsInBinaryTree {
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
Queue<TreeNode> next = new LinkedList<>();
List<Double> result = new LinkedList<>();
if (root == null) {
return result;
}
queue.offer(root);
double sum = 0.0;
int count = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
sum += node.val;
count++;
if (node.left != null) {
next.offer(node.left);
}
if (node.right != null) {
next.offer(node.right);
}
if (queue.isEmpty()) {
result.add(sum / count);
sum = 0.0;
count = 0;
queue.addAll(next);
next.clear();
}
}
return result;
}
}