450. Delete Node in a BST
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 53% Topics: Tree, Binary Search Tree, Binary Tree
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(h)
# Space: O(h)
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return root
if root.val > key:
root.left = self.deleteNode(root.left, key)
elif root.val < key:
root.right = self.deleteNode(root.right, key)
else:
if not root.left:
right = root.right
del root
return right
elif not root.right:
left = root.left
del root
return left
else:
successor = root.right
while successor.left:
successor = successor.left
root.val = successor.val
root.right = self.deleteNode(root.right, successor.val)
return root
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions