Delete Nodes and Return Forest
viaLeetCode
Problem Given the root of a binary tree with distinct values and a list to_delete, remove every node whose value is in to_delete. Deletions split the tree into a forest; return the roots of the remaining trees.
Input / Output
- Input: root, int[] to_delete.
- Output: list of forest roots (any order).
Constraints
- Up to 1000 nodes, distinct values; O(n) expected.
Example
- root = [1,2,3,4,5,6,7], to_delete = [3,5] → forests [[1,2,null,4],[6],[7]].
Expected approach
- Post-order DFS returning the node's replacement (itself or null if deleted): put to_delete in a set; recurse children first, reattach their results; if the current node is deleted, its surviving children become new roots; the original root joins the answer only if it survives. Post-order matters — children must know their fate before the parent detaches them. O(n) time, O(h) stack.
asked …