-
Notifications
You must be signed in to change notification settings - Fork 8
/
AverageOfLevelsInBinaryTree.java
51 lines (44 loc) · 1.27 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
47
48
49
50
51
package breadthfirstsearch;
// Source : https://leetcode.com/problems/average-of-levels-in-binary-tree/
// Id : 637
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020-03-19
// Topic : Breadth First Search
// Other :
// Tips :
// Result : 99.18% 24.76%
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class AverageOfLevelsInBinaryTree {
// 99.18% 1 ms 24.76%
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans = new LinkedList<>();
if (root == null)
return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
double sum = 0.0;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
sum += node.val;
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
ans.add(sum / size);
}
return ans;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}