forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AverageLevelsOfBinaryTree.java
32 lines (31 loc) · 1.12 KB
/
AverageLevelsOfBinaryTree.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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class AverageLevelsOfBinaryTree {
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
int count = 0;
List<Double> result = new ArrayList<>();
result.add(0.0);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
if (current == null && queue.isEmpty()) break;
if (current == null) {
queue.add(null);
result.set(result.size() - 1, result.get(result.size() - 1) / count);
result.add(0.0);
count = 0;
continue;
}
count++;
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
result.set(result.size() - 1, result.get(result.size() - 1) + current.val);
}
result.set(result.size() - 1, result.get(result.size() - 1) / count);
return result;
}
}