# 1110. Delete Nodes And Return Forest

```
T: O(n)
S: O(n)
```

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
        Set<TreeNode> result = new HashSet<>();
        result.add(root);

        Set<Integer> toDelete = new HashSet<>();
        for (int d : to_delete) {
            toDelete.add(d);
        }
        dfs(root, toDelete, result);

        return new ArrayList(result);
    }
    private TreeNode dfs(TreeNode node, Set<Integer> toDelete, Set<TreeNode> result) {
        if (node == null) {
            return null;
        }
        TreeNode res = node;
        if (toDelete.contains(node.val)) { // current node is deleting, so children become the root of new tree

            if (node.left != null) {
                result.add(node.left);
            }
            if (node.right != null) {
                result.add(node.right);
            }
            res = null; // return null
            result.remove(node); // remove itself in result
        }
        node.left = dfs(node.left, toDelete, result); // receive return value from children to link back to current node
        node.right = dfs(node.right, toDelete, result);
        return res;
    }
}

/***
This question is not to delete a tree and move a node ...(not 450 -> quite hard!)

is breaking a tree into "several trees"! so become a forest! -> 
!!!!key!!!: "so result only add "root" for each tree!""

ex: if only delete 2
   1
 2.  3
4 5. 6 7   

then 
4, 5 become 2 new roots for 2 trees 
1 is still root (so that's why need to re-link, I mean this -> node.left = dfs(node.left, toDelete, result); 
dfs will return null -> node.left = null)

so ans is [1,null, 3,6, 7] [4] [5]. (3 trees)

ex: if delete 1
then root become 2, 3 -> 2 trees

T: O(n)
S: O(n)
 */
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/tree/binary-tree-classic/1110.-delete-nodes-and-return-forest.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
