Skip to content

LC 1973 [M] Count Nodes Equal to Sum of Descendants

Code with Senpai edited this page Feb 3, 2022 · 1 revision
# 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
Clone this wiki locally