AlgoInsight

DSA problem

Delete Nodes And Return Forest

MediumTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop300AmazonGoogleMicrosoftBloomberg

Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes whose values are in to_delete, the remaining forest is the set of disjoint trees. Return the roots of the trees in the remaining forest in any order.

The trick is to perform a post-order traversal. When we visit a node, we recursively process its children first; each recursive call returns either the (possibly trimmed) subtree rooted at that child, or null if the child itself was deleted. Only after both children have been resolved do we decide what to do with the current node.

If the current node's value is in to_delete, its surviving children become new roots of the forest (we add any non-null child to the result), and we return null to our parent so the parent's pointer to us is severed. If the current node is not to be deleted, we return it unchanged so the parent keeps the link.

There is one boundary case worth highlighting: the original root might be deleted, in which case any of its surviving subtrees that were not added inside the recursion must still be included in the answer. A clean way to handle this is to seed the result with the root if it survives — equivalently, treat the root's parent as a virtual deleted node so the same rule applies uniformly. The whole algorithm runs in O(n + d) time, where d = |to_delete|, using a hash set for O(1) deletion lookups and O(h) recursion space.

Examples

Example 1
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Explanation: Deleting 3 detaches 6 and 7 as new tree roots. Deleting 5 leaves no surviving subtrees (it had no children). The forest is the tree rooted at 1 (with 5 removed) plus singletons 6 and 7.
Example 2
Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]
Explanation: Deleting 3 (a leaf) leaves the original tree minus that leaf; the rest stays connected.
Example 3
Input: root = [1,2,3], to_delete = [1]
Output: [[2],[3]]
Explanation: The root is deleted, so its two children become roots of separate trees in the forest.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchhash-table

Browse all DSA problems