Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
- def getMin(x):
- while x.left:
- x=x.left
- return x.val
- def delete(root,key):
- if not root:return None
- if root.val<key:
- root.right=delete(root.right,key)
- elif root.val>key:
- root.left=delete(root.left,key)
- else:
- #if it lead
- if not root.left and not root.right:
- root=None
- #if it has one child
- elif not root.left:
- root=root.right
- elif not root.right:
- root=root.left
- #if it has two children
- else:
- swap=getMin(root.right)
- root.val=swap
- root.right=delete(root.right,swap)
- return root
- return delete(root,key)
Advertisement
Add Comment
Please, Sign In to add comment