给你一棵二叉树的根节点 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);
}
};