-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path637.cpp
More file actions
32 lines (30 loc) · 793 Bytes
/
Copy path637.cpp
File metadata and controls
32 lines (30 loc) · 793 Bytes
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
/**
* 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) {
if (!root) return {};
vector<double> res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
long sum = 0;
int cnt = q.size();
for (int qs = cnt; qs > 0; qs--) {
root = q.front(); q.pop();
sum += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
res.push_back((double)sum / cnt);
}
return res;
}
};