Skip to content

Commit f64745c

Browse files
committed
feat: add 637 AverageOfLevelsInBinaryTree
1 parent 81cc4c4 commit f64745c

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

.idea/misc.xml

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.nphausg.leetcode.easy;
2+
3+
import com.nphausg.leetcode.utils.TreeNode;
4+
5+
import java.util.*;
6+
7+
/**
8+
* <a href="https://leetcode.com/problems/average-of-levels-in-binary-tree">637. Average of Levels in Binary Tree</a>
9+
*/
10+
public class AverageOfLevelsInBinaryTree {
11+
public List<Double> averageOfLevels(TreeNode root) {
12+
List<Double> result = new ArrayList<>();
13+
if (root == null) {
14+
return Collections.emptyList();
15+
}
16+
Queue<TreeNode> queue = new LinkedList<>();
17+
queue.offer(root);
18+
while (!queue.isEmpty()) {
19+
long sum = 0;
20+
int size = queue.size();
21+
List<Integer> level = new ArrayList<>();
22+
for (int i = 0; i < size; i++) {
23+
TreeNode node = queue.poll();
24+
sum += node.val;
25+
if (node.left != null) {
26+
queue.offer(node.left);
27+
}
28+
if (node.right != null) {
29+
queue.offer(node.right);
30+
}
31+
}
32+
result.add(sum / (double) size);
33+
}
34+
return result;
35+
}
36+
}

0 commit comments

Comments
 (0)