lintcode 1115. Average of Levels in Binary Tree

给定非空二叉树,以数组的形式返回每一层上的节点的平均值。

样例
样例 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值