leetcode/1110.Delete-Nodes-And-Return-Forest/README.md
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:
1000.1 and 1000.to_delete.length <= 1000to_delete contains distinct values between 1 and 1000.给出二叉树的根节点 root,树上每个节点都有一个不同的值。如果节点值在 to_delete 中出现,我们就把该节点从树上删去,最后得到一个森林(一些不相交的树构成的集合)。返回森林中的每棵树。你可以按任意顺序组织答案。
提示:
func delNodes(root *TreeNode, toDelete []int) []*TreeNode {
if root == nil {
return nil
}
res, deleteMap := []*TreeNode{}, map[int]bool{}
for _, v := range toDelete {
deleteMap[v] = true
}
dfsDelNodes(root, deleteMap, true, &res)
return res
}
func dfsDelNodes(root *TreeNode, toDel map[int]bool, isRoot bool, res *[]*TreeNode) bool {
if root == nil {
return false
}
if isRoot && !toDel[root.Val] {
*res = append(*res, root)
}
isRoot = false
if toDel[root.Val] {
isRoot = true
}
if dfsDelNodes(root.Left, toDel, isRoot, res) {
root.Left = nil
}
if dfsDelNodes(root.Right, toDel, isRoot, res) {
root.Right = nil
}
return isRoot
}