Count Nodes Equal to Average of Subtree
给一个二叉树, 求树中有几个node的左子树和右子树的平均值等于root的值。、
这题就算dfs算一下即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = 0;
public int averageOfSubtree(TreeNode root) {
if(root == null)
return 0;
dfs(root);
return res;
}
public int[] dfs(TreeNode root) {
if(root == null)
return new int[]{0,0};
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int sum = left[0] + right[0] + root.val;
int count = left[1] + right[1] + 1;
if(Math.floor(sum / count) == root.val)
res++;
return new int[]{sum, count};
}
}