Delete Tree Nodes

You're given a tree with n nodes rooted at node 0. Each node has a value, and you need to remove entire subtrees whose sum equals zero.

The tree is represented by:
nodes - the total number of nodes
value[i] - the value of the i-th node
parent[i] - the parent of the i-th node (parent[0] = -1 for root)

Goal: Remove all subtrees with zero sum and return the count of remaining nodes.

Example: If a subtree has nodes with values [3, -2, -1], the sum is 0, so we remove the entire subtree including all its descendants.

Input & Output

example_1.py — Basic Tree Pruning
$ Input: nodes = 7, parent = [-1,0,0,1,1,2,2], value = [1,-2,4,1,1,-2,2]
Output: 2
💡 Note: Node 2 has children 5(-2) and 6(2), so subtree sum = 4 + (-2) + 2 = 4 ≠ 0. Node 1 has children 3(1) and 4(1), so subtree sum = (-2) + 1 + 1 = 0, so we remove this entire subtree. Final tree has only nodes 0 and 2 remaining.
example_2.py — Single Node Tree
$ Input: nodes = 1, parent = [-1], value = [0]
Output: 0
💡 Note: The root node has value 0, so its subtree sum is 0. We remove the entire tree, leaving 0 nodes.
example_3.py — No Pruning Needed
$ Input: nodes = 5, parent = [-1,0,1,2,3], value = [1,2,3,4,5]
Output: 5
💡 Note: This is a linear tree: 0(1)→1(2)→2(3)→3(4)→4(5). No subtree has sum 0, so all nodes remain.

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
  • The given input is guaranteed to represent a valid tree

Visualization

Tap to expand
Root(1)sum=2, count=2A(-2)sum=0, count=0B(3)sum=3, count=1C(1)PRUNEDD(1)PRUNEDDFS Processing Order & Results1. Process C(1): sum=1, count=12. Process D(1): sum=1, count=13. Process A(-2): sum=-2+1+1=0 → PRUNE entire subtree4. Process B(3): sum=3, count=1 → KEEP5. Process Root(1): sum=1+0+3=4, count=1+0+1=2
Understanding the Visualization
1
Build Tree Structure
Convert parent array into adjacency list representation
2
Start Post-Order DFS
Begin traversal from root, but process children before parents
3
Calculate Leaf Sums
Process leaf nodes first - their sum equals their value
4
Propagate Sums Upward
Each parent sums its value with all children's subtree sums
5
Prune Zero Subtrees
When subtree sum equals 0, immediately mark entire subtree as removed
6
Count Remaining Nodes
Return final count of nodes that weren't pruned
Key Takeaway
🎯 Key Insight: Process children before parents (post-order) to calculate subtree sums in one pass, immediately pruning zero-sum subtrees without redundant calculations.
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
28.4K Views
Medium Frequency
~15 min Avg. Time
896 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