统计值等于子树平均值的节点数

给你一棵二叉树的根节点 root ,找出并返回满足要求的节点数,要求节点的值等于其 子树 中值的 平均值 。

注意:

n 个元素的平均值可以由 n 个元素 求和 然后再除以 n ,并 向下舍入 到最近的整数。
root 的 子树 由 root 和它的所有后代组成。
 

示例 1:


输入:root = [4,8,5,0,1,null,6]
输出:5
解释:
对值为 4 的节点:子树的平均值 (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4 。
对值为 5 的节点:子树的平均值 (5 + 6) / 2 = 11 / 2 = 5 。
对值为 0 的节点:子树的平均值 0 / 1 = 0 。
对值为 1 的节点:子树的平均值 1 / 1 = 1 。
对值为 6 的节点:子树的平均值 6 / 1 = 6 。
示例 2:


输入:root = [1]
输出:1
解释:对值为 1 的节点:子树的平均值 1 / 1 = 1。
 

提示:

树中节点数目在范围 [1, 1000] 内
0 <= Node.val <= 1000

链接:https://leetcode.cn/problems/count-nodes-equal-to-average-of-subtree

class Solution {
public:
    int res=0;//用于计数的全局变量
    int count=0;//count代表当前递了多少次
    int averageOfSubtree(TreeNode* root) {
        dfs(root);
        return res;
    }
    int dfs(TreeNode* root)//后序遍历
    {
        if(root==NULL)
            return 0;
        int currcount=count;//currcount代表现在递的层数
        count++;
        int l=dfs(root->left);
        int r=dfs(root->right);
        int val=l+r+root->val;
        if(root->val==val/(count-currcount))//(count-currcount)代表子树有多少节点
            res++;
        return val;
    }
};
class Solution {
public:
        int res=0;
    int averageOfSubtree(TreeNode* root) {
        dfs(root,res);
        return res;
    }
    void dfs(TreeNode * root,int res)
    {
        if(root==NULL)
        return;
        int sum=0,sumnode=0;
        count(root,sum,sumnode);
        if(root->val==sum/sumnode)
        res++;
        dfs(root->left,res);
        dfs(root->right,res);
    }
    void count(TreeNode * root,int &sum,int &sumnode)
    {
        if(root==NULL)
        return;
        sumnode++;//记录子树节点的个数
        sum+=root->val;//把子树每个节点的值加到sum上
        count(root->left,sum,sumnode);
        count(root->right,sum,sumnode);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值