Delete Tree Nodes Problem
Description
LeetCode Problem 1273.
A tree rooted at node 0 is given as follows:
- The number of nodes is
nodes; - The value of the
i^thnode isvalue[i]; - The parent of the
i^thnode isparent[i].
Remove every subtree whose sum of values of nodes is zero.
Return the number of the remaining nodes in the tree.
Example 1:
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
Output: 2
Example 2:
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2]
Output: 6
Constraints:
1 <= nodes <= 10^4parent.length == nodes0 <= parent[i] <= nodes - 1parent[0] == -1which indicates that0is the root.value.length == nodes-10^5 <= value[i] <= 10^5- The given input is guaranteed to represent a valid tree.
Solution
Approach: Post-Order DFS
First build the list of children of every node from parent. Then a depth-first search returns two numbers for the subtree rooted at node i:
- its sum of values, and
- how many of its nodes remain after the deletions.
For node i, start with its own value and a count of 1, then add the sum and the remaining count of each child's subtree. If the total sum is 0, the whole subtree is removed, so its remaining count becomes 0. The answer is the remaining count of the root.
Two points make this correct. The sum must include the values of nodes that were removed below: removing a zero-sum subtree does not change its parent's sum, since the removed part adds 0. And the children are finished before the parent decides (post-order), so when a subtree is removed, everything already counted inside it is dropped with it.
Complexity: O(n) time and O(n) space for n nodes (children lists and the recursion stack).
class Solution:
def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int:
children = [[] for _ in range(nodes)]
for i in range(1, nodes):
children[parent[i]].append(i)
def dfs(i: int) -> Tuple[int, int]:
# (sum of the subtree rooted at i, nodes left in it after the deletions)
total, count = value[i], 1
for c in children[i]:
child_total, child_count = dfs(c)
total += child_total
count += child_count
if total == 0:
count = 0 # the whole subtree is removed
return total, count
return dfs(0)[1]