Delete Node in a BST solution explained
To delete a node from a binary search tree, first find it by comparing the key and going left or right. If it has no children, remove it; if it has one child, let that child take its place; if it has two, replace it with its in-order successor (the smallest key in its right subtree) and then delete that successor from the right subtree. The work follows one root-to-leaf path, so it costs O(h) time, where h is the height of the tree.
By Evin JohnPublished 8 min read
The problem in our words
You are given the root of a binary search tree with distinct keys and one key to remove. Delete the node holding that key, if it exists, so that what remains is still a binary search tree: smaller keys on the left of every node, larger on the right. Return the root of the resulting tree. If the key is not in the tree, return the tree unchanged.
Before: After deleting 22:
40 40
/ \ / \
22 61 27 61
/ \ \ / \ \
15 30 75 15 30 75
/ / /
27 70 70Node 22 has two children, so it cannot simply vanish. Its in-order successor is 27, the leftmost node under its right child. Moving 27 into 22's position keeps every key on the left smaller and every key on the right larger. Deleting 61 instead is the one-child case: 75 and its subtree move up to hang off 40. Deleting 15 is the leaf case. Deleting 50, which is absent, changes nothing.
Why interviewers like it
Searching and inserting in a BST are each a few lines. Deletion is the operation where people discover whether they really understand the ordering rule, because the two-child case needs a replacement that preserves it. Interviewers also listen for the detail that the root itself can be deleted, which is why the function returns a root instead of nothing. Expect one of these follow-ups:
- Use the predecessor instead. The largest key in the left subtree works just as well. Alternating between the two can help stop a tree from leaning to one side after many deletions.
- Move nodes, not values. In some codebases nodes carry more than a key, so copying values is not allowed. Then you must relink the successor node itself (the JavaScript version below does this).
- Delete every key in a range. A trim operation that walks the tree once is better than many single deletions.
- Keep the tree balanced. Plain deletion can make a tree lopsided; AVL and red-black trees rebalance with rotations afterward.
A simple but costly baseline
Read the tree in order into a sorted list, drop the key, and rebuild a balanced tree from what is left by picking middles recursively. It is easy to get right and the result is even balanced. The cost is O(n) time and O(n) extra memory for every deletion, and the tree's shape changes completely, which callers holding references to nodes might not expect. It is a reasonable answer to mention first and a good oracle for testing.
The O(h) approach: three cases
Search recursively. If the key is smaller than the current node, delete it from the left subtree and store the returned subtree root as the new left child. Larger means the same on the right. When you land on the node to delete, check its children. No left child: return the right child (this covers the leaf, where the right child is also null). No right child: return the left child. Two children: find the successor by stepping right once and then left as far as possible, copy its key into the current node, and delete that key from the right subtree. The successor has no left child, so that second deletion always hits one of the easy cases.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delete_node(root, key):
if root is None:
return None
if key < root.val:
root.left = delete_node(root.left, key)
elif key > root.val:
root.right = delete_node(root.right, key)
else:
if root.left is None:
return root.right
if root.right is None:
return root.left
successor = root.right
while successor.left:
successor = successor.left
root.val = successor.val
root.right = delete_node(root.right, successor.val)
return rootThe JavaScript version is iterative and moves the successor node itself rather than its value. It tracks the parent of the node being deleted, so it can reattach the replacement on the correct side, and returns the replacement directly when the deleted node was the root.
function deleteNode(root, key) {
let parent = null;
let node = root;
while (node !== null && node.val !== key) {
parent = node;
node = key < node.val ? node.left : node.right;
}
if (node === null) return root;
let replacement;
if (node.left === null) {
replacement = node.right;
} else if (node.right === null) {
replacement = node.left;
} else {
let succParent = node;
let succ = node.right;
while (succ.left !== null) {
succParent = succ;
succ = succ.left;
}
if (succParent !== node) {
succParent.left = succ.right;
succ.right = node.right;
}
succ.left = node.left;
replacement = succ;
}
if (parent === null) return replacement;
if (parent.left === node) parent.left = replacement;
else parent.right = replacement;
return root;
}The subtle line is the check succParent !== node. When the successor is the deleted node's own right child, it already sits in place on the right, so only its left pointer changes. Otherwise the successor's right subtree is handed to its old parent, and the successor adopts both of the deleted node's subtrees.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| In-order list, remove, rebuild | O(n) | O(n) |
| Recursive three-case deletion | O(h) | O(h) call stack |
| Iterative deletion with parent tracking | O(h) | O(1) |
| Same, in a self-balancing tree | O(log n) | Depends on the rebalancing scheme |
Say what h means for this input. A tree built from random insertions tends to stay shallow, but one built from sorted insertions is a chain, and then O(h) is O(n).
Edge cases
- The key is not present: the tree comes back unchanged.
- The tree is empty: return null.
- The only node is deleted: return null.
- The root is deleted while it has two children: the root's key or node changes, and the caller must use the returned root.
- The successor is the right child itself (it has no left subtree).
- A long skewed tree: the recursive version can exceed Python's default recursion limit of about a thousand frames, which the iterative one avoids.
Mistakes to avoid
- Forgetting to assign the result of the recursive call back to root.left or root.right, so nothing actually changes.
- Picking the right child as the replacement without checking it has no left subtree, which breaks the ordering.
- Copying the successor's key but then deleting the original key again, instead of the successor's key, from the right subtree.
- Losing the successor's right subtree when moving nodes.
- Returning nothing when the root is deleted, leaving the caller with a stale pointer.
How to explain it out loud
Fictional example
- Candidate
- I search like a lookup. Once I find the node there are three cases, and the first two just return the existing child.
- Candidate
- With two children I need a key that is bigger than everything on the left and smaller than everything else on the right. The smallest key in the right subtree is exactly that.
- Candidate
- I copy it up and delete it from the right subtree. It has no left child, so that second delete is an easy case.
- Interviewer
- Cost?
- Candidate
- One path down plus one path to the successor, so O(h). For a balanced tree that is log n; for a chain it is n.
Related walkthroughs
Convert Sorted Array to BST is the rebuild step used in the baseline above. All Nodes Distance K in a Binary Tree is another problem where tracking a node's parent is the trick. Sum Root to Leaf Numbers is a gentler tree recursion, and LRU Cache is good practice for careful pointer relinking.
Where Natively fits
Pointer-heavy questions are easiest to learn by explaining them to someone. In a practice session on Mac or Windows, Natively can take a screenshot of the problem and, if you get stuck on the two-child case, offer a hint about the successor instead of the finished code. Afterward its transcript shows whether you mentioned the root-deletion case without being prompted. Details are on the AI interview assistant page.
Questions people ask
How do you delete a node from a binary search tree?
Find it by comparing keys. A leaf is removed, a node with one child is replaced by that child, and a node with two children takes its in-order successor's key, which is then deleted from the right subtree.
What is the in-order successor in a BST?
The smallest key larger than the node's key, found by going to the right child once and then left as far as possible. It never has a left child.
What is the time complexity of deleting from a BST?
O(h), where h is the tree's height: O(log n) for a balanced tree and O(n) for a skewed one.
Why does BST deletion return the root?
Because the deleted node might be the root itself, in which case the tree's root changes and the caller needs the new one.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
