LC 1973 [M] Count Nodes Equal to Sum of Descendants - ALawliet/algorithms GitHub Wiki

# 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:
        self.count = 0
        
        def postorder(node):
            if not node:
                return 0
            
            L = postorder(node.left)
            R = postorder(node.right) 
            
            if L + R == node.val:
                self.count += 1
            
            return L + R + node.val
        
        postorder(root)
        
        return self.count