You are given an integer array parent representing a forest of rooted trees with n nodes, where parent[i] is the parent of the i-th node.
If parent[i] == i, then node i is the root of a tree.
Otherwise, parent[i] < i, meaning that the parent always has a smaller index.
Every node has exactly one parent, except the root.
You are also given an integer nodeToDelete, representing a node to delete.
Your task is to delete nodeToDelete and all of its descendants from the forest.
Deletion is done in-place by setting parent[x] = -1 for every deleted node x.
Return the updated parent array.
def deleteSubtree(parent, nodeToDelete):
n = len(parent)
# Mark the root node of the subtree itself
parent[nodeToDelete] = -1
for i in range(n):
if parent[i] == -1: # already deleted
continue
j = i
# Walk upward until root or deletion target
while parent[j] != j and parent[j] != -1 and parent[j] != nodeToDelete:
j = parent[j]
# If we reached nodeToDelete, delete this node too
if parent[j] == nodeToDelete:
parent[i] = -1
return parent