[leetcode]637. Average of Levels in Binary Tree
Analysis
周五啦~—— [嘻嘻~]
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
显然用BFS解决~
Implement
/**
* 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> res;
if(!root)
return res;
queue<TreeNode* > q;
q.push(root);
while(!q.empty()){
double sum = 0;
int leaves = q.size();
for(int i=0; i<leaves; i++){
TreeNode* tmp = q.front();
q.pop();
sum += tmp->val;
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
}
res.push_back(sum/(double)leaves);
}
return res;
}
};