1110. Delete Nodes And Return Forest - cocoder39/coco39_LC GitHub Wiki

1110. Delete Nodes And Return Forest

Deconstruct the problem:

  1. delete nodes and return root rather than forest
def deleteNodesAndReturnRoot(cur):
            if not cur:
                return
            
            if cur.val in to_delete:
                return None
            
            cur.left = helper(cur.left, False)
            cur.right = helper(cur.right, False)
            return cur

deleteNodesAndReturnRoot() remove target nodes from tree and returns the root of tree

  1. delete nodes and return forest -> passing an array to collect tress in forest
class Solution:
    def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
        to_delete = set(to_delete)
        res = []
        
        def helper(cur, isRoot):
            if not cur:
                return
            
            if cur.val in to_delete:
                helper(cur.left, True)
                helper(cur.right, True)
                return None
            
            if isRoot:
                res.append(cur)
            
            cur.left = helper(cur.left, False)
            cur.right = helper(cur.right, False)
            return cur
            
        helper(root, True)
        return res