Delete Nodes And Return Forest - Problem
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.
Input & Output
Example 1 — Basic Deletion
$
Input:
root = [1,2,3,4,5,6,7], to_delete = [3,5]
›
Output:
[[1,2,null,4],[6],[7]]
💡 Note:
Delete nodes 3 and 5. Node 1 remains as root of tree [1,2,null,4]. Children 6 and 7 of deleted node 3 become separate tree roots.
Example 2 — Root Deletion
$
Input:
root = [1,2,4,null,3], to_delete = [1]
›
Output:
[[2,null,3],[4]]
💡 Note:
Delete root node 1. Its children 2 and 4 become new tree roots. Node 3 remains as child of 2.
Example 3 — Single Node
$
Input:
root = [1], to_delete = [1]
›
Output:
[]
💡 Note:
Delete the only node, resulting in an empty forest.
Constraints
-
The number of nodes in the given tree is at most
1000. -
Each node has a distinct value between
1and1000. -
to_delete.length <= 1000 -
to_deletecontains distinct values between1and1000.
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree [1,2,3,4,5,6,7] with delete list [3,5]
2
Delete Process
Remove nodes 3 and 5, children become new roots
3
Forest Result
Three separate trees: [1,2,null,4], [6], [7]
Key Takeaway
🎯 Key Insight: Deleted nodes split the tree - their children become forest roots
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code