```
vector<double> averageOfLevels(TreeNode* root) {
queue<TreeNode*> q;
vector<double> r;
if (root) {
q.push(root);
}
while (!q.empty()) {
int s = q.size();
double sum = 0;
for (int i = 0; i < s; i++) {
TreeNode* f = q.front();
q.pop();
sum += f->val;
if (f->left) {
q.push(f->left);
}
if (f->right) {
q.push(f->right);
}
}
r.push_back(sum / s);
}
return r;
}
```