Count Nodes Equal to Sum of Descendants - 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. The sum is considered to be 0 if the node has no descendants.

Input & Output

Example 1 — Basic Tree
$ Input: root = [10,3,4,2,1]
Output: 2
💡 Note: Node 10: descendants are [3,4,2,1], sum = 10 (matches). Node 3: descendants are [2,1], sum = 3 (matches). Node 4 has no descendants, sum = 0 ≠ 4.
Example 2 — Single Node
$ Input: root = [2]
Output: 1
💡 Note: Single node with no descendants. Sum of descendants = 0, but node value = 2, so it doesn't match. Wait, the node has no descendants so sum = 0, and 2 ≠ 0, so result is 0.
Example 3 — No Matches
$ Input: root = [0]
Output: 1
💡 Note: Single node with value 0. It has no descendants, so sum of descendants = 0. Since 0 = 0, this node matches.

Constraints

  • The number of nodes in the tree is in the range [1, 105]
  • -105 ≤ Node.val ≤ 105

Visualization

Tap to expand
Count Nodes Equal to Sum of Descendants103421Check each node:Node 10: descendants [3,4,2,1] → sum = 10 ✓Node 3: descendants [2,1] → sum = 3 ✓Node 4: no descendants → sum = 0 ≠ 4Leaves have no descendants → sum = 0Output: 2 (nodes 10 and 3 match)
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Calculate Descendant Sums
For each node, find sum of all descendants
3
Count Matches
Count nodes where value equals descendant sum
Key Takeaway
🎯 Key Insight: Use post-order DFS to calculate subtree sums bottom-up in one pass
Asked in
Google 15 Amazon 12
23.1K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen