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: 0
💡 Note: Single node with value 2 and no descendants. Sum of descendants = 0, but node value = 2, so 2 ≠ 0 and it doesn't match.
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 Descendants INPUT Binary Tree Structure 10 3 4 2 1 root = [10, 3, 4, 2, 1] Level-order traversal representation of tree ALGORITHM STEPS 1 Post-order DFS Visit children before parent 2 Calculate Subtree Sum Sum = left + right subtrees 3 Check Condition node.val == descendant sum? 4 Return Total Sum node.val + descendant sum Calculation Example: Node 10: sum=3+4+2+1=10 OK Node 3: sum=2+1=3 OK Node 4: sum=0 (leaf) NO Node 2: sum=0 (leaf) NO Node 1: sum=0 (leaf) NO FINAL RESULT Nodes matching condition 10 = 3+4+2+1 3 = 2+1 4 2 1 Match No Match Output: 2 Key Insight: Post-order traversal (left --> right --> root) enables single-pass solution with O(n) time complexity. Each recursive call returns the total sum of its subtree, allowing parent nodes to compute descendant sums without re-traversing. Leaf nodes have sum = 0, so they only match if their value is also 0. TutorialsPoint - Count Nodes Equal to Sum of Descendants | Optimized DFS - Single Pass
Asked in
Google 15 Amazon 12
23.2K 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