# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def equalToDescendants(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
ans = 0
def dfs(node):
nonlocal ans
if node is None:
return 0
tot = dfs(node.left) + dfs(node.right)
if tot == node.val:
ans += 1
return tot + node.val
dfs(root)
return ans
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var ans int
func dfs(root *TreeNode) int{
if root==nil{
return 0
}
node_sum:=0
//左子树之和
node_sum+=dfs(root.Left)
//右子树之和
node_sum+=dfs(root.Right)
//左右子树之和等于当前值
if node_sum==root.Val{
ans++
}
//
root.Val+=node_sum
return root.Val
}
func equalToDescendants(root *TreeNode) int {
ans=0
dfs(root)
return ans
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//考虑从下往上递归传值
func equalToDescendants(root *TreeNode) int {
res:=0
var sum func(node *TreeNode)int
sum=func(node *TreeNode)int{
//递归到空节点时,认为它是0
if node==nil{return 0}
//获得当前节点左子树和右子树的和值,left和right
left:=sum(node.Left)
right:=sum(node.Right)
//如果当前节点的值等于左子树值加右子树值,res++
if node.Val==left+right{res++}
//向上返回此树的和值
return node.Val+left+right
}
_=sum(root)
return res
}