思路:就是在每层遍历的时候,把值存在sum里,最后push到result里时取个平均值,注意定义vector时类型是double。还是最初二叉树的模板略加改动。
题解c++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
queue<TreeNode*> que;
if(root!=NULL) que.push(root);
vector<double> result;
while(!que.empty())
{
int size=que.size();
double sum=0;
for(int i=0;i<size;i++)
{
TreeNode* node=que.front();
que.pop();
sum+=node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(sum/size);
}
return result;
}
};