Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def delNodes(self, root, to_delete):
- '''
- Use bottom up appraoch: if my left/right is part of delete list, I will cut my left/right branch
- if I am part of delete list, I will add my left/right pointers #if exist# => return True
- otherwise: return False (meaning I'm not part of delete list, don't worry about me)
- P.S: if my left/right pointers were part of delete list they would have already been taken care of in my previous recurion call, that's why bottom-up approach is better and no need to track the parent pointer.
- '''
- if root is None:
- return []
- del_set=set(to_delete)
- def delete(root,del_set,root_list):
- if root is None:
- return False
- pleft=delete(root.left,del_set,root_list)
- pright=delete(root.right,del_set,root_list)
- if pleft:
- root.left=None
- if pright:
- root.right=None
- if root.val in del_set:
- if root.left:
- root_list.append(root.left)
- if root.right:
- root_list.append(root.right)
- return True
- return False
- root_list=[]
- if root.val not in del_set:
- root_list.append(root)
- delete(root,del_set,root_list)
- return root_list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement