-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelOrderAverageBinaryTree
43 lines (40 loc) · 1.14 KB
/
LevelOrderAverageBinaryTree
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root)
{
// List<List<Integer>> answer = new LinkedList<>();
List<Double> doubAns= new LinkedList<>();
if(root==null)
return doubAns;
Queue<TreeNode> cache = new LinkedList<>();
cache.add(root);
while(!cache.isEmpty())
{
// List<Integer> currLevel = new LinkedList<>();
int n = cache.size();
long sum=0, count=0;
for(int i =0;i<n;i++)
{
TreeNode temp=cache.poll();
// currLevel.add(temp.val);
sum+=temp.val;
count++;
if(temp.left!=null)
{cache.add(temp.left);}
if(temp.right!=null)
cache.add(temp.right);
}
// answer.add(currLevel);
doubAns.add((sum*1.0)/count);
}
return doubAns;
}
}