Advertisement
Guest User

Delete Nodes and Return Forest

a guest
Mar 15th, 2021
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
  2.     delete = set(to_delete)
  3.     forest = []
  4.  
  5.     def _prune(node, isRoot):
  6.         if node is None:
  7.             return
  8.         if node.val in delete:
  9.             _prune(node.left, True)
  10.             _prune(node.right, True)
  11.         else:
  12.             if isRoot:
  13.                 forest.append(node)
  14.             _prune(node.left, False)
  15.             _prune(node.right, False)
  16.  
  17.             if node.left and node.left.val in delete:
  18.                 node.left = None
  19.  
  20.             if node.right and node.right.val in delete:
  21.                 node.right = None
  22.  
  23.     _prune(root, True)
  24.  
  25.     return forest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement