/**
* 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 == NULL)
{
return res;
}
queue<TreeNode*>q;
q.push(root);
int curCount = 1; //当前这一层有几个结点
while(!q.empty())
{
double numSum = 0;
int nextCount = 0; //下一层有几个结点
for(int i = 0; i < curCount; i++)
{
TreeNode* cur = q.front();
q.pop();
numSum += cur->val;
if(cur->left != NULL)
{
q.push(cur->left);
nextCount++;
}
if(cur->right != NULL)
{
q.push(cur->right);
nextCount++;
}
}
res.push_back(numSum/curCount);
curCount = nextCount;
}
return res;
}
};
[leetcode] 637. 二叉树的层平均值
最新推荐文章于 2024-09-03 18:29:17 发布