Count Nodes Equal to Sum of Descendants
给一个二叉树, 问上面有多少个node的val等于左子树和右子树的和.
这题就travseal 一下就行了
/**
* 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 equalToDescendants(TreeNode root) {
count(root);
return res;
}
public int count(TreeNode root){
if(root == null)
return 0;
int left = count(root.left);
int right = count(root.right);
if(root.val == left+right)
res++;
return root.val + left + right;
}
}