-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaverage-of-levels-in-binary-tree.cpp
53 lines (44 loc) · 1.17 KB
/
average-of-levels-in-binary-tree.cpp
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
43
44
45
46
47
48
49
50
51
52
53
//Runtime: 16 ms
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root)
{
vector<double>res;
if(!root)
return res;
queue<pair<int,TreeNode*> > Q;
Q.push(make_pair(1, root));
int maxlvl = 0;
vector<int>temp;
while(!Q.empty())
{
pair<int,TreeNode*> t = Q.front();
Q.pop();
if(t.first > maxlvl)
{
maxlvl++;
if(temp.size() > 0)
{
double sum = 0.0;
for(int a : temp)
sum += a;
res.push_back(sum/temp.size());
}
temp.clear();
}
temp.push_back(t.second->val);
if(t.second->left)
Q.push(make_pair(t.first+1, t.second->left));
if(t.second->right)
Q.push(make_pair(t.first+1, t.second->right));
}
if(!temp.empty())
{
double sum = 0;
for(int a:temp)
sum += a;
res.push_back(sum/temp.size());
}
return res;
}
};