A tree rooted at node 0 is given as follows:

  • The number of nodes is nodes
  • The value of the ith node is value[i]
  • The parent of the ith node is parent[i]

Remove every subtree whose sum of values of nodes is zero.

Return the number of the remaining nodes in the tree.

Input & Output

Example 1 — Basic Tree Pruning
$ Input: parent = [-1,0,0,1,1,1,1], value = [1,-3,4,0,-2,-1,-2]
Output: 2
💡 Note: Node 3 and its descendants form subtree with sum 0 + (-2) + (-1) + (-2) = -5. Wait, let me recalculate: Node 1 has value -3, children 3,4,5,6. Subtree sum = -3 + 0 + (-2) + (-1) + (-2) = -8. Only nodes 0 and 2 remain with values 1 and 4.
Example 2 — Single Node Tree
$ Input: parent = [-1], value = [0]
Output: 0
💡 Note: Root node has value 0, so entire tree is removed. No nodes remain.
Example 3 — No Removal Needed
$ Input: parent = [-1,0,1], value = [1,2,3]
Output: 3
💡 Note: No subtree has sum 0. All nodes remain: root(1) -> child(2) -> grandchild(3)

Constraints

  • 1 ≤ nodes ≤ 104
  • parent.length == nodes
  • 0 ≤ parent[i] ≤ nodes - 1
  • parent[0] == -1 which indicates that 0 is the root
  • value.length == nodes
  • -105 ≤ value[i] ≤ 105

Visualization

Tap to expand
Delete Tree Nodes Problem OverviewOriginal Tree1-340-2-1Sum CalculationNode 1 subtree: -3 + 0 + (-2) + (-1) = -6Root subtree: 1 + (-6) + 4 = -1No zero-sum subtrees foundAll nodes keptResult: 7Final Tree1-340-2-1All 7 nodes remain (no zero-sum subtrees)
Understanding the Visualization
1
Input Tree
Tree with parent array and node values
2
Calculate Sums
Find subtrees with sum = 0
3
Remove & Count
Delete zero-sum subtrees, count remaining
Key Takeaway
🎯 Key Insight: Use post-order DFS to calculate subtree sums and prune zero-sum subtrees in single traversal
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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