Delete Node in a BST
Difficulty: Medium · Pattern: Trees & BST · LeetCode #450
Delete the node with value key from a BST (if it exists) and return the possibly updated root. The result must still be a valid BST.
When the node has two children there are two classic choices: replace it with its inorder successor or with its inorder predecessor. The tests accept either one, as long as you copy the value and delete the successor/predecessor node.
Examples
text
root = [5,3,6,2,4,null,7], key = 3 → [5,4,6,2,null,null,7] (or [5,2,6,null,4,null,7])
root = [5,3,6,2,4,null,7], key = 0 → unchanged
root = [], key = 0 → []Hints
- First find the node using BST search.
- No children: remove it. One child: return that child to the parent. Two children: what value can take its place without breaking the ordering?
Approach
Recursive, returning the new subtree root:
text
delete(node, key):
if not node: return null
if key < node.val: node.left = delete(node.left, key)
elif key > node.val: node.right = delete(node.right, key)
else:
if not node.left: return node.right # 0 or 1 child
if not node.right: return node.left
s = node.right; while s.left: s = s.left # inorder successor
node.val = s.val
node.right = delete(node.right, s.val) # remove the successor (it has no left child)
return nodeThe successor is the smallest value in the right subtree, so putting it at the node keeps everything on the left smaller and everything on the right larger.
Complexity
Time: O(h). Space: O(h) recursion.
Python solution
def deleteNode(root, key):
if not root:
return None
if key < root.val:
root.left = deleteNode(root.left, key)
elif key > root.val:
root.right = deleteNode(root.right, key)
else:
if not root.left:
return root.right
if not root.right:
return root.left
s = root.right
while s.left:
s = s.left
root.val = s.val
root.right = deleteNode(root.right, s.val)
return rootJavaScript solution
function deleteNode(root, key) {
if (!root) return null;
if (key < root.val) root.left = deleteNode(root.left, key);
else if (key > root.val) root.right = deleteNode(root.right, key);
else {
if (!root.left) return root.right;
if (!root.right) return root.left;
let s = root.right;
while (s.left) s = s.left;
root.val = s.val;
root.right = deleteNode(root.right, s.val);
}
return root;
}