1110. Delete Nodes And Return Forest

#### QUESTION:

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.

Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]]

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.

#### SOLUTION:

``````class Solution {
public List<TreeNode> delNodesResult = new ArrayList<>();
public List<TreeNode> delNodesResultcopy = new ArrayList<>();
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
for(int del:to_delete){
delNodesResultcopy.clear();// 将子树遍历集合情况
delNodesHelper(del);
}
return delNodesResult;
}

public void delNodesHelper(int del){
for(TreeNode node : delNodesResult){
if(delNodesInTree(null,node,del)) return; // 因为节点的所有值都是不重复的，那么就可以判断需要del的值只可能在一个子树中，找到了，后续的子树就可以不用遍历了。
}
}

public boolean delNodesInTree(TreeNode parent,TreeNode node,int del){ // 因为需要将父节点置为null，所以将父节点也一并传过来
if(node == null) return false;
if(node.val == del) {
if(parent!=null){ // 如果父节点为null，就说明父节点是需要删除的，那么就需要将集合中的之前存的树进行删除，再添加父节点的两个子树
if(parent.left!= null && parent.left.val == node.val) parent.left=null;
if(parent.right!=null && parent.right.val == node.val) parent.right = null;
}else{
Iterator<TreeNode> iterator = delNodesResult.iterator();
while (iterator.hasNext()){
TreeNode root = iterator.next();
if(root.val == node.val) iterator.remove();
}
}