Problem Description
Given the root of a binary tree, return the number of nodes where the node's value is equal to the sum of the values of its descendants. A descendant is any node on the path from the current node down to a leaf. For a node with no descendants, the descendant sum is considered to be 0.
Key Insights
- Use a postorder traversal (depth-first search) to compute the sum of each subtree.
- For each node, compare its value with the sum of its descendants (left subtree sum + right subtree sum).
- Leaf nodes have a descendant sum of 0, so count them if their value is 0.
- Use recursion to both compute subtree sums and update the count in a single DFS pass.
Space and Time Complexity
Time Complexity: O(n) – Each node is visited once. Space Complexity: O(h) – Recursive call stack, where h is the height of the tree.
Solution
Perform a postorder DFS to calculate the sum of values for each subtree. For every node:
- Recursively get the sum of the left subtree.
- Recursively get the sum of the right subtree.
- Check if the node's value equals the sum of its descendants (left sum + right sum).
- Increment a counter if the condition is met.
- Return the total sum of the subtree rooted at that node (node's value + left sum + right sum).
This approach efficiently computes the required sums and counts matching nodes in one pass.