# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
ans = []
s = set(to_delete)
def dfs(node: Optional[TreeNode]) -> Optional[TreeNode]:
if node is None: return None
node.left = dfs(node.left)
node.right = dfs(node.right)
if node.val not in s: return node
if node.left: ans.append(node.left)
if node.right: ans.append(node.right)
return None
if dfs(root): ans.append(root)
return ans
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func delNodes(root *TreeNode, to_delete []int) []*TreeNode {
ret := []*TreeNode{}
st := make(map[int]int)
for _,v := range to_delete{
st[v] = v
}
var postOrder func(parent *TreeNode,node *TreeNode)
postOrder = func (parent *TreeNode,node *TreeNode) {
if node == nil{
return
}
postOrder(node,node.Left)
postOrder(node,node.Right)
if _,ok := st[node.Val];ok{
if parent != nil {
if parent.Left == node {
parent.Left = nil
}
if parent.Right == node {
parent.Right = nil
}
}
if node.Left != nil {
ret = append(ret,node.Left)
}
if node.Right != nil {
ret = append(ret,node.Right)
}
}
}
postOrder(nil,root)
if _,ok := st[root.Val];!ok {
ret = append(ret,root)
}
return ret
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
def dfs(root, hasParent):
if not root:
return False
toDelete = root.val in to_delete
# a new root = (keep root) and (has no parent)
if not toDelete and not hasParent:
res.append(root)
# delete left = (delete left) and (keep root)
if dfs(root.left, not toDelete):
root.left = None
# delete right = (delete right) and (keep root)
if dfs(root.right, not toDelete):
root.right = None
return toDelete
to_delete = set(to_delete)
res = []
dfs(root, False)
return res