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 1 and 1000.
  • to_delete.length <= 1000
  • to_delete contains distinct values between 1 and 1000.

Visualization

Tap to expand
Delete Nodes And Return Forest1234567Original TreeDelete [3,5]Tree 1124Tree 26Tree 37Forest: [[1,2,null,4], [6], [7]]When nodes 3 and 5 are deleted, their children become new tree roots
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
78.9K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen