Delete Nodes And Return Forest - Problem
Imagine you have a binary tree representing a family tree or organizational structure, and you need to remove certain nodes while preserving the remaining structure. When nodes are deleted, their children become the roots of new, separate trees - creating what we call a forest.
Given the root of a binary tree where each node has a distinct value, and an array to_delete containing values of nodes to remove, your task is to:
- Delete all nodes whose values appear in the
to_deletearray - Return the roots of all remaining trees in the resulting forest
- When a node is deleted, its children (if any) become new tree roots
Example: If you delete the root of a tree, its left and right children become separate tree roots. The order of the returned roots doesn't matter.
Input & Output
example_1.py โ Basic Tree Deletion
$
Input:
root = [1,2,3,4,5,6,7], to_delete = [3,5]
โบ
Output:
[[1,2,null,4],[6],[7]]
๐ก Note:
Deleting nodes 3 and 5 creates three separate trees: the main tree with root 1 (node 3's children 6,7 become separate roots), and isolated nodes 6 and 7 as single-node trees.
example_2.py โ Root Deletion
$
Input:
root = [1,2,4,null,3], to_delete = [1]
โบ
Output:
[[2,null,3],[4]]
๐ก Note:
When the root node 1 is deleted, its children (2 and 4) become the roots of new trees in the forest. Node 2 keeps its child 3.
example_3.py โ Single Node Tree
$
Input:
root = [1], to_delete = [1]
โบ
Output:
[]
๐ก Note:
Edge case: deleting the only node in the tree results in an empty forest (no remaining trees).
Constraints
- The number of nodes in the given tree is at most 1000
- Each node has a distinct value
- 1 โค Node.val โค 1000
- 1 โค to_delete.length โค 1000
- All values in to_delete are unique
Visualization
Tap to expand
Understanding the Visualization
1
Original Forest
Start with a connected tree structure
2
Mark for Deletion
Identify nodes to delete using hash set lookup
3
Perform Deletions
Remove marked nodes, creating gaps in the tree
4
Identify New Roots
Children of deleted nodes become new forest roots
5
Return Forest
Collect all independent tree roots
Key Takeaway
๐ฏ Key Insight: Use a hash set for O(1) deletion checks and single DFS pass where each node determines if it becomes a forest root based on its survival and parent's deletion status.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code