Delete Node in a BST
Advertisement
Problem
Given a BST root and a key, delete the node with that key and return the updated root.
Key insight: Three cases — node is leaf, node has one child, node has two children (replace with in-order successor).
Approach — Recursive BST Delete
find node → if two children: replace val with inorder-successor, delete successor
Solutions
// C
TreeNode* inorderSuccessor(TreeNode* node) {
while (node->left) node = node->left;
return node;
}
TreeNode* deleteNode(TreeNode* root, int 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;
TreeNode* succ = inorderSuccessor(root->right);
root->val = succ->val;
root->right = deleteNode(root->right, succ->val);
}
return root;
}
// C++
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return nullptr;
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;
auto succ = root->right;
while (succ->left) succ = succ->left;
root->val = succ->val;
root->right = deleteNode(root->right, succ->val);
}
return root;
}
// Java
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) 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 == null) return root.right;
if (root.right == null) return root.left;
TreeNode succ = root.right;
while (succ.left != null) succ = succ.left;
root.val = succ.val;
root.right = deleteNode(root.right, succ.val);
}
return root;
}
// JavaScript
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 succ = root.right;
while (succ.left) succ = succ.left;
root.val = succ.val;
root.right = deleteNode(root.right, succ.val);
}
return root;
}
# Python
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
succ = root.right
while succ.left:
succ = succ.left
root.val = succ.val
root.right = deleteNode(root.right, succ.val)
return root
Complexity
- Time: O(h) — h = tree height
- Space: O(h) recursion stack
Key Insight
In-order successor is the leftmost node in the right subtree. Replace deleted node's value, then delete successor.
Advertisement