天天看点

Leecode 第 292 场周赛 6057. 统计值等于子树平均值的节点数

原题链接:6057. 统计值等于子树平均值的节点数

Leecode 第 292 场周赛 6057. 统计值等于子树平均值的节点数
Leecode 第 292 场周赛 6057. 统计值等于子树平均值的节点数

自己在考场上写的:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int Count(TreeNode* root)
    {
        if(!root) return 0;
        else if(!root->left && !root->right) return 1;
        else return Count(root->left)+Count(root->right)+1;
    }
    int sum(TreeNode* root)
    {
        if(!root) return 0;
        else if(!root->left && !root->right) return root->val;
        else return sum(root->left)+sum(root->right)+root->val;
    }
    int averageOfSubtree(TreeNode* root) {
        queue<TreeNode* > q;
        q.push(root);
        int res=0;
        while(!q.empty())
        {
            root=q.front(); q.pop();
            if(sum(root)/Count(root)==root->val) res++;
            if(root->left) q.push(root->left);
            if(root->right) q.push(root->right);
        }
        return res;
    }
};
           

参考别人的更简洁好看的代码:

继续练!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res=0;
    pair<int,int> dfs(TreeNode* root)
    {
        int x=1,y=root->val;
        if(root->left)
        {
            auto z=dfs(root->left);
            x+=z.first; y+=z.second;
        }
        if(root->right)
        {
            auto z=dfs(root->right);
            x+=z.first; y+=z.second;
        }
        if(y/x==root->val) res++;
        return {x,y};
    }
    int averageOfSubtree(TreeNode* root) {
        dfs(root);
        return res;
    }
};