-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path637.cpp
More file actions
80 lines (77 loc) · 2.15 KB
/
637.cpp
File metadata and controls
80 lines (77 loc) · 2.15 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
__________________________________________________________________________________________________
sample 20 ms submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> avg;
if(!root)
return avg;
queue<TreeNode*> Q;
TreeNode* curr = root;
Q.push(curr);
while(!Q.empty()){
int L = Q.size();
long sum = 0;
for(int i = 0; i < L; i++){
curr = Q.front();
Q.pop();
if(curr->left) Q.push(curr->left);
if(curr->right) Q.push(curr->right);
sum +=(curr->val);
}
avg.push_back((double)sum/L);
}
return avg;
}
};
static int speedup=[](){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
__________________________________________________________________________________________________
sample 21816 kb submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
vector<double> averageOfLevels(TreeNode* root)
{
vector<double> res;
vector<TreeNode*> cur, next;
cur.push_back(root);
while (not cur.empty())
{
long long s = 0;
for (auto it : cur)
{
s += it->val;
if (it->left) next.push_back(it->left);
if (it->right) next.push_back(it->right);
}
res.push_back(static_cast<double>(s)/cur.size());
cur.swap(next);
next.clear();
}
return res;
}
};
__________________________________________________________________________________________________