We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 5610b9d commit b8508a9Copy full SHA for b8508a9
java/637-Average-of-Levels-in-Binary-Tree.java
@@ -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