Problem Description
Given the root of a binary tree with distinct node values, delete all nodes whose values are found in the list to_delete. After deletion, the remaining nodes form a forest (a collection of disjoint trees). Return the root nodes of each tree in the forest. The result can be returned in any order.
Key Insights
- Use a recursive depth-first search (DFS) to traverse the tree.
- At each node, determine if it should be deleted based on the to_delete set.
- When deleting a node, ensure that its non-deleted children are added as new roots in the forest.
- Postorder traversal (processing children before the current node) is beneficial so that children are processed before potentially deleting the parent.
- Using a set for to_delete items allows for fast lookup.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes since each node is visited once. Space Complexity: O(N) for the recursion stack and the set used to store deletion values and resulting forest.
Solution
We employ a DFS approach to traverse the tree in a postorder manner, processing left and right children first. For each node:
- Check if the node should be deleted by looking it up in the to_delete set.
- If the node is flagged for deletion, add its non-null children as potential new roots to the forest.
- Return null for a deleted node and the node itself if it is kept. This recursive process ensures that any subtree whose root gets deleted properly adds any potential subtrees to the answer list before the node is removed.