754. Delete Tree Nodes
Given a tree with n nodes labeled from 0 to n-1 in the form of a parent array where parent[i] is the parent of node i. The root node is always labeled 0, and parent[0] = -1.
You are also given an array value where value[i] is the value associated with the node i.
You need to delete all nodes and their subtrees where the sum of all values in the subtree is 0. Return the number of remaining nodes.
Example 1:
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
Output: 2
Explanation:
- Subtree rooted at node 1: (-2 + 0) = -2 β Kept.
- Subtree rooted at node 2: (4 -2 -1 -1) = 0 β Removed.
- Remaining nodes are 0 and 1.
Example 2:
Input: nodes = 7, parent = [-1, 0, 0, 1, 2, 2, 2], value = [1, -2, 4, 0, -2, -1, -2]
Output: 6
Explanation:
-Subtree rooted at node 0: (1 -2 + 0 + 4 -2 -1 -2) = -2 β Kept
-Subtree rooted at node 1: (-2 + 0) = -2 β Kept
-Subtree rooted at node 2: (4 -2 -1 -2) = -1 β Kept
-Subtree rooted at node 3: 0 β Removed
-Subtree rooted at node 4: -2 β Kept
-Subtree rooted at node 5: -1 β Kept
-Subtree rooted at node 6: -2 β Kept
Only node 3 is removed, so remaining nodes are 6/
Now Your Turn!
Pick the correct output for the given inputInput: nodes=5, parent = [-1, 0, 0, 1, 1]Β , value = [1, -1, 3, -1, -2]
Still unsure what the problem is asking ?
Letβs go through a few more examples, step by step, to make it clearer.
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.