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;
    }
};
发布了369 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/104003220
今日推荐