Skip to content

Commit 212c3a5

Browse files
add 637
1 parent 6876ab0 commit 212c3a5

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Your ideas/fixes/algorithms are more than welcome!
2020

2121
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
2222
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
23+
|637|[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_637.java) | O(n) |O(1) | Easy |
2324
|634|[Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_634.java) | O(n) |O(1) | Medium | Math
2425
|633|[Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_633.java) | O(logn) |O(1) | Easy | Binary Search
2526
|628|[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_628.java) | O(nlogn) |O(1) | Easy |
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.fishercoder.solutions;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
5+
import java.util.ArrayList;
6+
import java.util.LinkedList;
7+
import java.util.List;
8+
import java.util.Queue;
9+
10+
/**
11+
* 637. Average of Levels in Binary Tree
12+
*
13+
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
14+
15+
Example 1:
16+
Input:
17+
3
18+
/ \
19+
9 20
20+
/ \
21+
15 7
22+
23+
Output: [3, 14.5, 11]
24+
Explanation:
25+
26+
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
27+
Note:
28+
The range of node's value is in the range of 32-bit signed integer.
29+
*/
30+
public class _637 {
31+
32+
public List<Double> averageOfLevels(TreeNode root) {
33+
List<Double> result = new ArrayList<>();
34+
if (root == null) return result;
35+
Queue<TreeNode> queue = new LinkedList<>();
36+
queue.offer(root);
37+
while (!queue.isEmpty()) {
38+
int size = queue.size();
39+
double sum = 0.0;
40+
for (int i = 0; i < size; i++) {
41+
TreeNode curr = queue.poll();
42+
if (curr != null) {
43+
sum += curr.val;
44+
}
45+
if (curr.left != null) {
46+
queue.offer(curr.left);
47+
}
48+
if (curr.right != null) {
49+
queue.offer(curr.right);
50+
}
51+
}
52+
result.add(sum/size);
53+
}
54+
return result;
55+
}
56+
57+
}

0 commit comments

Comments
 (0)