Delete Tree Nodes - Problem
A tree rooted at node 0 is given as follows:
- The number of nodes is
nodes - The value of the
ith node isvalue[i] - The parent of the
ith node isparent[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code