15% off all plans & roadmaps Use code
See plansDelete Nodes And Return Forest
- LeetCode 1110
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
Updated
TL;DR: Delete every node whose value appears in to_delete, then return the roots of the trees that remain. Handle children before parents in one pass, so each deleted node can promote its surviving children to new roots.
Problem
You are given the root of a binary tree. Each node in the tree has a distinct value.
Remove every node whose value appears in to_delete. What is left is a forest, which is a disjoint union of trees.
Return the roots of the trees in the remaining forest. You may return them 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.
Constraints that matter
- The tree has at most 1000 nodes, so recursion depth can reach 1000. Python's default recursion limit is also 1000, so the traversal needs an explicit stack.
- Values are distinct, so each value identifies exactly one node. A hash set of deleted values then answers each node check in O(1).
- to_delete has at most 1000 values, so building a set costs O(M). Scanning the list for every node would cost O(N * M), which is about 10^6 steps at this size.
- Values in to_delete may not appear in the tree. A lookup that misses leaves the node in place.
Hints
Hint 1
This problem has a tree pattern where a node's outcome depends on its children.
Hint 2
The recursive form is a postorder DFS.
Solution
Intuition
This problem has a tree pattern where a node's outcome depends on its children. Deleting a node does two things. It cuts the link from its parent, and it turns its surviving children into roots of new trees.
It is like pruning a family tree after a generation is removed. The hash set is the list of removed names, and each surviving child of a removed person becomes the head of its own family.
The pattern is recursive postorder traversal. Postorder means children are finished before their parent. When a parent is deleted, the pointers below it are already final, so any non-null child is a real new root.
The naive version searches the whole forest for each value in to_delete. That costs O(N * M). A hash set answers 'is this node deleted?' in constant time, and one bottom-up pass handles every deletion at once. Recognize this shape when the answer for a node depends on what its subtrees produce.
Worked example
Input: root = [1, 2, 4, null, 3], to_delete = [3] Output: [[1, 2, 4]] Explanation: Node 3 is deleted, which cuts it from node 2. Nodes 1, 2 and 4 stay connected, so the forest has one tree rooted at 1.
The Recursive Postorder Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Recursive Postorder Traversal
Approach 1: Postorder cleanup with a hash setOptimalRecursive Postorder Traversal
The recursive form is a postorder DFS. Each call processes its left and right subtrees first, then decides about its own node. The call returns the node if it survives, or null if it is deleted, and the parent stores that result in its child pointer.
The code here does the same work without recursion. It first lists the nodes with a stack, so every parent appears before its children. It then walks that list backwards, which settles each child before its parent. Python's default recursion limit is 1000. A skewed tree with 1000 nodes can exceed it, so the iterative form is safer in every language.
For each node in that backwards walk, cut any deleted child. If the node is deleted itself, promote its surviving children to the forest. The root gets one last check, because no parent exists to receive it.
Why it is correct. Children are handled before parents, so every node's pointers are final when its turn comes. A node becomes a forest root exactly when its parent is deleted or it has no parent. Each node is checked once, so no surviving root is missed or counted twice.
Steps
- Put every value from
to_deleteinto a hash set. - Start a stack at the root. Pop a node, record it in
order, then push its non-null children. - Repeat the pop step until the stack is empty. Every parent now sits before its children in
order. - Walk
orderfrom the last entry to the first. Children are settled before their parents. - For each node, set
leftto null if the left child's value is in the set. Do the same forright. - If the node itself is in the set, append each non-null child to the forest as a new root.
- After the walk, append the root to the forest if its value is not in the set.
- Return the forest.
Dry run
Example tree: node 1 has left child 2 and right child 4. Node 2 has right child 3. The set is {3}.
Stack walk: pop 1, record it, push 2 and 4. Pop 4, record it. Pop 2, record it, push 3. Pop 3, record it. The list order is [1, 4, 2, 3], so walking it backwards visits 3, 2, 4, 1.
| Step | Node | Action | Forest |
|---|---|---|---|
| 1 | 3 | 3 has no children. 3 is deleted, so nothing is promoted. | [] |
| 2 | 2 | Right child 3 is in the set, so set 2.right to null. Node 2 survives. | [] |
| 3 | 4 | No children. Node 4 survives. | [] |
| 4 | 1 | Left child 2 and right child 4 both survive, so no cuts. Node 1 survives. | [] |
| End | root 1 | Root is not in the set, so append it. | [1] |
The trace ends with forest [1], and the tree still holds 2 and 4 under it. That matches the expected [[1,2,4]].
Complexity
| Time | O(N + M) |
|---|---|
| Space | O(N + M) |
N is the number of tree nodes and M is the length of to_delete. Building the set inserts M values once, which is O(M). The stack walk pushes and pops each node once. The backwards loop checks each node with O(1) set lookups, so both take O(N).
The list and stack hold at most N node references, and the set holds at most M values. The extra space is therefore O(N + M). The returned forest is not counted as extra space.
PythonTested in our runner
class Solution:
def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[Optional[TreeNode]]:
to_delete_set = set(to_delete)
forest = []
if root is None:
return forest
# Build preorder (push right before left) so parents come before children and output order is natural.
order = []
stack = [root]
while stack:
node = stack.pop()
order.append(node)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
# Surviving children of deleted nodes become new roots; remember them as node objects.
new_roots = set()
# Walk backwards so children are settled before parents.
for node in reversed(order):
if node.left and node.left.val in to_delete_set:
node.left = None
if node.right and node.right.val in to_delete_set:
node.right = None
if node.val in to_delete_set:
if node.left:
new_roots.add(node.left)
if node.right:
new_roots.add(node.right)
# Collect roots in preorder so the forest order matches the recursive order.
if root.val not in to_delete_set:
new_roots.add(root)
for node in order:
if node in new_roots and node.val not in to_delete_set:
forest.append(node)
return forestCommon mistakes
- Checking
node.val in to_deleteagainst the list instead of a set. Each list scan costs O(M), so the whole pass becomes O(N * M). Buildto_delete_setonce and test membership against it. - Returning the node for every call, including deleted ones, such as
return nodein the deleted branch. The parent keeps a pointer to a deleted node, so the node stays in the tree. Return null, or set the parent's child pointer to null, for deleted nodes. - Walking the list top-down, so parents run before children. A deleted parent then promotes a child that still points at a deleted grandchild. Walk the list backwards so children are settled first.
- Appending
forest.append(node.left)without a null check. Missing children then enter the forest as null entries. Check each child before you append it. - Forgetting the root. The root has no parent to receive a promoted node, so a surviving root never reaches the forest unless you check it after the loop.
- Using plain recursion in Python on a deep tree. A 1000-node chain needs about 1000 nested calls, which can hit the default limit of 1000. Use the explicit stack shown here.
Edge cases
- The root is deleted, for example root [1,2,3] with to_delete [1]. The forest is the two subtrees, so the answer is [[2],[3]]. The root never appears in the output.
- Every node is deleted, for example root [1] with to_delete [1]. The forest is empty, so return [].
- No value in to_delete appears in the tree. The whole tree survives, so return it as the only tree.
- A parent and its child are both deleted, for example root [1,2,3] with to_delete [1,3]. Node 2 survives and becomes the root, so the answer is [[2]].
- A deleted leaf, for example root [1,2] with to_delete [2]. Nothing is promoted, and the answer is [[1]].
- Maximum size: a chain of 1000 nodes with values 1 to 1000, where every even value is deleted. Each odd value becomes its own single-node tree, so the answer has 500 roots. The iterative version handles the depth without recursion errors.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Delete Nodes And Return Forest, with how to answer them.
Unlock the follow-upsDelete Nodes And Return Forest FAQ
What is the time complexity of Delete Nodes And Return Forest?
The time is O(N + M), where N is the number of tree nodes and M is the length of to_delete. Each node is visited a constant number of times, and building the set costs O(M). Under the given limits, both sizes are at most 1000.
Why use a postorder traversal for Delete Nodes And Return Forest?
Deleting a node changes its parent's child pointer and creates new roots from its children. Postorder settles each child before the parent reads it, so the parent sees final pointers. One pass covers every deletion without searching the tree again.
Can Delete Nodes And Return Forest be solved in O(1) extra space?
Not with the approach on this page, because the stack and node list can each hold N references. Constant extra space is possible with a boolean array sized 1001 and a Morris-style traversal, since the value bound is fixed. Without that bound, the membership check needs a set of size M.
Why convert to_delete to a hash set?
A set answers membership in O(1) average time. Scanning the list for each node costs O(M) and turns the pass into O(N * M). At these limits that is about 10^6 steps, but the set is the idiomatic choice.
Why does the Python recursive version fail on deep trees?
Python's default recursion limit is 1000, and each recursive call adds a frame. A skewed tree with about 1000 nodes needs roughly 1000 nested frames, which can exceed the limit. The iterative version avoids this, so use it when depth can reach the limit.
Asked at
See which companies ask this — Pro
Related problems
- House Robber III · same technique: Recursive Postorder Traversal
- Delete Leaves With a Given Value · same technique: Recursive Postorder Traversal
- All Nodes Distance K in Binary Tree · same technique: Recursive Postorder Traversal
- Find Leaves of Binary Tree · same technique: Recursive Postorder Traversal
- Binary Tree Maximum Path Sum · same technique: Recursive Postorder Traversal
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Level Order Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Right Side View · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)