1973. Count Nodes Equal to Sum of Descendants

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1973

# 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 res
                res += 1
            return root.val + l + r

        res = 0
        dfs(root)
        return res