1. Description
Given a binary tree, return the average value of the nodes on each level.
2. Solution
BFS.
3. Code
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
if(root==NULL) return ans;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int l = q.size();
double sum=0;
for(int i=0;i<l;i++){
TreeNode* t = q.front();
q.pop();
sum+=t->val;
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
ans.push_back(sum*1.0/l);
}
return ans;
}