The Delete Nodes And Return Forest interview question asks you to take a binary tree and a list of values to delete. After removing the specified nodes, the tree breaks into several disjoint subtrees (a "forest"). You need to return a list of the roots of these new trees. This Delete Nodes And Return Forest coding problem requires managing connectivity while traversing the hierarchy.
Companies like Microsoft and Pinterest ask this to evaluate your mastery of Binary Tree interview patterns and recursive state management. It requires you to track whether a node's parent was deleted, which determines if the current node becomes a new root in the resulting forest.
The most effective pattern is Post-order Traversal (DFS) with a Hash Set for deletion lookups.
Tree: 1 is root, children 2, 3. Nodes to delete: [2].
2. It's in the delete list.2 had children (say 4, 5), they would be added to the forest result list.1 sets its left child to null.1 was the original root and wasn't deleted, the result is [root(1), root(4), root(5)].to_delete list.Practice returning "state" from recursive calls. In this problem, the recursive function often returns the node itself (or null if deleted) to the caller, which allows the parent to easily update its child pointers. This "return and update" technique is vital for tree-pruning tasks.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Path Sum IV | Medium | Solve | |
| Find Duplicate Subtrees | Medium | Solve | |
| Create Binary Tree From Descriptions | Medium | Solve | |
| Lowest Common Ancestor of a Binary Tree IV | Medium | Solve | |
| Most Frequent Subtree Sum | Medium | Solve |