给定非空二叉树,以数组的形式返回每一层上的节点的平均值。
样例
样例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的节点的平均值是3,第一层的平均值是14.5, 第二层的平均值11,因此需要返回[3, 14.5, 11]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the binary tree of the root
* @return: return a list of double
*/
vector<double> averageOfLevels(TreeNode * root) {
// write your code here
queue<TreeNode*> a;
queue<TreeNode*> b;
vector<double>res;
if(root==NULL) return res;
a.push(root);
while(!a.empty()||!b.empty())
{
if(!a.empty())
{
double sum=0.0;
double count=0.0;
while(!a.empty())
{
if(a.front()->left) b.push(a.front()->left);
if(a.front()->right) b.push(a.front()->right);
sum+=a.front()->val;
count++;
a.pop();
}
res.push_back(sum/count);
}
if(!b.empty())
{
double sum=0.0;
double count=0.0;
while(!b.empty())
{
if(b.front()->left) a.push(b.front()->left);
if(b.front()->right) a.push(b.front()->right);
sum+=b.front()->val;
count++;
b.pop();
}
res.push_back(sum/count);
}
}
return res;
}
};