Delete Nodes And Return Forest Problem
Description
LeetCode Problem 1110.
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Example 2:
Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]
Constraints:
- The number of nodes in the given tree is at most
1000. - Each node has a distinct value between
1and1000. to_delete.length <= 1000to_deletecontains distinct values between1and1000.
Solution
Approach: Post-Order DFS
A node ends up as the root of a tree in the forest exactly when it is kept and either it is the original root or its parent is deleted. So deleting a node turns each of its kept children into a new root.
Do a post-order traversal with a function prune(node) that deletes what it must in this subtree and returns what is left of it: node itself, or null if node was deleted.
- First prune both children, and store the results back in
node.leftandnode.right. This cuts the links to deleted children, so trees in the answer never point to deleted nodes. - If
nodeis kept, return it. - If
nodeis deleted, its remaining children (already pruned) become roots: add them to the answer, then returnnullso the parent drops its link.
After the call on the root, add the root to the answer too if it was kept. Putting the values to delete in a hash set (or a boolean array, since values are at most 1000) makes each check O(1).
Children are handled before their parent on purpose: when a node is added to the forest, its own subtree has already been cleaned up.
Complexity: O(n + d) time for n nodes and d values to delete, and O(n + d) space for the set and the recursion stack.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
doomed = set(to_delete)
forest = []
# Returns what is left of this subtree: the node itself, or None if it was deleted.
def prune(node: Optional[TreeNode]) -> Optional[TreeNode]:
if node is None:
return None
node.left = prune(node.left)
node.right = prune(node.right)
if node.val not in doomed:
return node
# The node goes away: its surviving children become roots of their own trees.
if node.left:
forest.append(node.left)
if node.right:
forest.append(node.right)
return None
if prune(root): # the original root survived
forest.append(root)
return forest