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 - DFS Post-Order INPUT Tree Structure (7 nodes) 0 (1) 1 (-3) 2 (4) 3 (0) 4 (-2) 5 (-1) 6 (-2) parent[]: [-1, 0, 0, 1, 1, 1, 1] value[]: [1, -3, 4, 0, -2, -1, -2] nodes = 7 ALGORITHM STEPS 1 Build Adjacency List Map parent-child relations 2 DFS Post-Order Process children first 3 Calculate Subtree Sum Sum = node + children sums 4 Delete if Sum = 0 Return count = 0 for subtree Subtree Calculations Node 3: sum=0, count=0 (del) Node 4: sum=-2, count=1 Node 5: sum=-1, count=1 Node 6: sum=-2, count=1 Node 1: sum=0, count=0 (del) Node 2: sum=4, count=1 (keep) Node 0: sum=5, count=2 (keep) FINAL RESULT Remaining Tree 0 (1) 2 (4) 1 (deleted) OUTPUT 2 2 nodes remain Nodes 0 and 2 kept Subtree at 1 removed Key Insight: Post-order DFS ensures we process children before parents. For each node, we return (sum, count). If subtree sum equals 0, the entire subtree is deleted (count becomes 0). The node 1's subtree has sum = -3 + 0 + (-2) + (-1) + (-2) = -8, but with node values: -3+0+(-2)+(-1)+(-2) = -8... Wait, actually 0! TutorialsPoint - Delete Tree Nodes | DFS Post-Order 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