Delete Node in a BST Solutions in Python
Number 450
Difficulty Medium
Acceptance 43.2%
Link LeetCode
Other languages C++
Solutions
Python solution by haoel/leetcode
"""case 1: if node we want to delete has no children: simply delete itcase 2: if it has only one child, then replace it with its childcase 3: if it has two children, first find the inorder successor (or predecessor),then replace the node's value with successor's value, and finally delete this successor"""def deleteNode(self, root, key):if not root: return Noneif key < root.val:root.left = self.deleteNode(root.left, key)elif key > root.val:root.right = self.deleteNode(root.right, key)else:# if this node has only one child or no child:if not root.left:temp = root.rightroot = Nonereturn tempelif not root.right:temp = root.leftroot = Nonereturn temp# otherwise, find the inorder successor:curr = root.rightwhile curr.left:curr = curr.leftroot.val = curr.valroot.right = self.deleteNode(root.right, curr.val)return root