Count Nodes Equal to Sum of Descendants — LeetCode 1973 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
Problem
#1973
Reading time
4 min

The problem

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.

Example

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.

Python solution

Python
# 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

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1973. Count Nodes Equal to Sum of Descendants is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1973. Count Nodes Equal to Sum of Descendants?
LeetCode 1973. Count Nodes Equal to Sum of Descendants is rated Medium on LeetCode.
What is the time complexity of LeetCode 1973. Count Nodes Equal to Sum of Descendants?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1973. Count Nodes Equal to Sum of Descendants?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1973. Count Nodes Equal to Sum of Descendants cover?
LeetCode 1973. Count Nodes Equal to Sum of Descendants is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
Is LeetCode 1973. Count Nodes Equal to Sum of Descendants a premium problem?
Yes. LeetCode 1973. Count Nodes Equal to Sum of Descendants is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview