← 返回 snowflake 的题目列表Forest Parent Array Delete Node
类型:qbank
Given a forest encoded as an array where `parent[i]` stores node `i`'s parent index and each root has `parent[i] == i`, delete a specified node and return a new parent-index array that still satisfies the same representation constraints. The post confirms valid input and no null / None entries; the child-promotion rule should be clarified before coding.
Requirements
Input is an array representation of a forest. For every node index i, parent[i] stores the index of its parent.
A root node stores itself as parent: parent[i] == i.
Input is always valid and contains no NULL / None.
Delete one specified node and return the resulting parent array.
The output array must still use valid indices under the same rules after the deleted node is removed and remaining nodes are reindexed.
Clarify before coding how children of the deleted node should be repaired. A common convention is to promote direct children of the deleted node into roots, then shift all parent indices greater than the deleted index down by one.
Notes
The core difficulty is not tree traversal; it is maintaining parent-index validity after the array shrinks.
Build an old-index -> new-index map for every node except the deleted node. Then rewrite each remaining node's parent through that map.
If a remaining node's old parent is the deleted node, apply the agreed repair policy. Under root-promotion semantics, its new parent becomes its own new index.
Edge cases: deleting a root, deleting a leaf, single-node forest, multiple roots, and deleting a node whose parent index is greater than the deleted index.
Preparation
Implement the old-to-new index remapping approach and test it on a forest with multiple roots.
Walk through deletion of a root with two children and verify all shifted parent indices by hand.
Prepare one sentence to clarify child repair semantics before writing code.