题解 | #牛群平均重量#

牛群平均重量

https://www.nowcoder.com/practice/9b826d0a84034e8e8afd4c451f7d34e0

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return double浮点型vector
     */
    vector<double> averageOfLevels(TreeNode* root) {
        // write code here
        vector<double> ans;
        queue<TreeNode*> q;
        if (root == nullptr) {
            return ans;
        }
        q.push(root);
        while (q.size()) {
            int num = q.size();
            int sum = 0;
            int count = num;
            while (num--) {
                TreeNode* t = q.front();
                sum += t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
                q.pop();
            }
            ans.push_back(sum * 1.0 / count);
        }
        return ans;
    }
};

全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
05-27 11:41
已编辑
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务