Count Nodes Equal to Sum of Descendants Problem
Description
LeetCode Problem 1973.
Given the root of a binary tree, return the number of nodes where the value of the node is equal to the sum of the values of its descendants.
A descendant of a node x is any node that is on the path from node x to some leaf node. The sum is considered to be 0 if the node has no descendants.
Example 1:

Input: root = [10,3,4,2,1]
Output: 2
Explanation:
For the node with value 10: The sum of its descendants is 3+4+2+1 = 10.
For the node with value 3: The sum of its descendants is 2+1 = 3.
Example 2:

Input: root = [2,3,null,2,null]
Output: 0
Explanation:
No node has a value that is equal to the sum of its descendants.
Example 3:

Input: root = [0]
Output: 1
For the node with value 0: The sum of its descendants is 0 since it has no descendants.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 0 <= Node.val <= 10^5
Solution
Approach: DFS
Do a post-order traversal where the function returns the sum of the values in a subtree. For a node, the sum of its descendants is the returned sum of the left subtree plus that of the right subtree (a missing child gives 0). If that equals the node's value, count the node. Return the node's value plus both sums to the parent.
Sums can reach about 10^10, so use a 64-bit integer in languages with 32-bit int.
Complexity: time O(n), space O(h), where n is the number of nodes and h the height of the tree.
# 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:
def dfs(root):
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
if l + r == root.val:
nonlocal ans
ans += 1
return root.val + l + r
ans = 0
dfs(root)
return ans