Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node's value is in the range of 32-bit signed integer.
题目:对于给定的二叉树,计算每层节点的平均值,返回vector<double>
思路:如果动手做了二叉树的层次遍历,这道题就很简单,二叉树的遍历是得到一个二维的vector,因此只需要对每个vector求平均即可,即将原来的res.push_back(lvl)改为 ret.push_back(accumulate(lvl.begin(),lvl.end(),0.0)/lvl.size()),这是求平均值的代码。注意accumulate()初始值设为0.0。
代码:
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ret;
if(!root)
return ret;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
vector<int> lvl;
int size=q.size();
for(;size>0;size--){
TreeNode* node=q.front();
lvl.push_back(node->val);
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
ret.push_back(accumulate(lvl.begin(),lvl.end(),0.0)/lvl.size());//更改的地方
}
return ret;
}
};
AC,beats99%