Skip to content

Commit b8508a9

Browse files
Create 637-Average-of-Levels-in-Binary-Tree.java
1 parent 5610b9d commit b8508a9

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//Apply Breadth first search.
2+
//Asked in Amazon and Meta
3+
class Solution {
4+
public List<Double> averageOfLevels(TreeNode root) {
5+
List<Double> ans = new ArrayList<>();
6+
Queue<TreeNode> q = new LinkedList();
7+
q.offer(root);
8+
while (!q.isEmpty()) {
9+
int queue_size = q.size();
10+
double avg = 0;
11+
for (int i = 0; i<queue_size; i++) {
12+
TreeNode cur = q.poll();
13+
avg += cur.val;
14+
if (cur.left!=null)
15+
q.offer(cur.left);
16+
if (cur.right!=null)
17+
q.offer(cur.right);
18+
}
19+
ans.add(avg/queue_size);
20+
}
21+
return ans;
22+
}
23+
}

0 commit comments

Comments
 (0)