Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created May 1, 2018 14:00
Show Gist options
  • Save s4553711/94eaf4488fb86078bef69b14395b93ec to your computer and use it in GitHub Desktop.
Save s4553711/94eaf4488fb86078bef69b14395b93ec to your computer and use it in GitHub Desktop.
/**
* 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> ans;
if (root == NULL) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int n = q.size();
long long sum = 0;
for(int i = 0; i < n; i++) {
TreeNode* t = q.front();
q.pop();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
sum += t->val;
}
ans.push_back(static_cast<double>(sum) / n);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment