Problem Description
Given a tree with nodes numbered from 0 to n-1 (with 0 as the root), each node has a value provided in the array value[]. The parent array (with parent[0] = -1) indicates the tree structure. The task is to remove every subtree (i.e. a node and all its descendants) whose sum of node values is zero and then return the total number of nodes remaining in the tree.
Key Insights
- Construct the tree using an adjacency list from the given parent array.
- Use depth-first search (DFS) to traverse the tree in a postorder manner (process children before the parent).
- At each node, compute the total sum of the subtree (current node and its descendants).
- If the subtree sum is zero, consider all those nodes removed (i.e. contribute zero to the count).
- Finally, return the number of nodes retained (subtrees with non-zero sum).
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, since each node is visited once. Space Complexity: O(n), due to the recursion stack and auxiliary data structures (like the children list).
Solution
The solution involves first converting the parent list into a mapping of node to its children. Then, employing DFS from the tree's root, we compute both the sum of the subtree and the count of nodes that remain (if the subtree sum is zero, we remove that entire subtree). The DFS returns a tuple (subtree sum, count) for each node. This approach ensures every node is processed only once and allows the algorithm to correctly “prune” subtrees with a sum of zero.