Sub topic 12
Deleting from a BST
This chapter assumes you know the binary search tree (BST) property, how search and insertion work, and how to read recursive Python. Deletion is the hardest of the three basic BST operations because removing a node must leave the ordering property intact. The method depends on how many children the target node has.
The problem
A BST keeps every key in a node's left subtree smaller than the node's key, and every key in its right subtree larger. If you remove a node, its children need a new parent, and the ordering must still hold. Deletion first finds the node, as search does, and then splits into three cases.
| Case | Children of the target | Action |
|---|---|---|
| 1 | None (leaf) | Remove the node. Its parent gets `None` in that slot. |
| 2 | Exactly one | Replace the node with its only child. |
| 3 | Two | Copy the inorder successor's key into the node, then delete the successor from the right subtree. |
The code
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
def delete(node, key):
if node is None:
return None
if key < node.key:
node.left = delete(node.left, key)
elif key > node.key:
node.right = delete(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
succ = node.right
while succ.left:
succ = succ.left
node.key = succ.key
node.right = delete(node.right, succ.key)
return node
root = None
for k in [50, 30, 70, 20, 40, 60, 80, 65]:
root = insert(root, k)
for k in [20, 30, 50]:
root = delete(root, k)
out = []
inorder(root, out)
print("after deleting", k, ":", out)Each call returns the root of the subtree it was given, after the deletion. The caller stores that return value back into node.left or node.right. This is how a deleted child gets unlinked: the parent's pointer is overwritten with whatever the recursive call returns.
Walking through the three cases
Case 1: deleting a leaf
Delete 20 from the tree built above. The search goes 50, then 30, then 20. Node 20 has no left child, so the code returns node.right, which is None. Node 30's left pointer becomes None. The leaf case needs no separate branch, because the "no left child" test returns node.right, and that is None for a leaf.
Case 2: deleting a node with one child
After 20 is gone, node 30 has only a right child, 40. Deleting 30 reaches the branch node.left is None and returns node.right, which is node 40. Node 50's left pointer now points at 40. Every key in the moved subtree was already in the correct range for that position, so the BST property still holds.
Case 3: deleting a node with two children
Node 50, the root, has children 40 and 70. We cannot simply return one child, because the other subtree would be lost. Instead we find a replacement key that can sit at this position without breaking the ordering. Two keys qualify:
- The inorder successor is the smallest key in the right subtree. It is greater than everything on the left and no larger than anything else on the right.
- The inorder predecessor is the largest key in the left subtree. It is the mirror choice.
The code uses the successor. For root 50 the right subtree is rooted at 70. Walking left gives 60, which has no left child, so the successor is 60. The code copies 60 into the root and then deletes 60 from the right subtree. That second deletion is easy: the successor is the leftmost node of its subtree, so it has no left child. It is therefore a case 1 or case 2 deletion, never case 3 again. In this tree, 60 has a right child 65, so 65 takes its place.
The final tree has root 60, with 65 and 80 under 70 as its right subtree and 40 as the left child.
Why the successor has no left child
The successor is found by going to the right child once and then left as far as possible. The loop stops at a node whose left is None. If that node had a left child, the loop would have continued. So the successor has at most one child, a right child, and deleting it never triggers the two-child case. This is why the recursion in case 3 terminates after a single extra step down the tree.
Cost
Deletion walks one root-to-node path to find the target. In case 3 it continues down to the successor, and the successor lies deeper than the target, so the total path is still no longer than the height of the tree. Each step does constant work. The cost is therefore O(h), where h is the height.
| Tree shape | Height | Deletion cost |
|---|---|---|
| Balanced, n nodes | about log2 n | O(log n) |
| Skewed (a chain) | n − 1 | O(n) |
Deleting never needs more than O(h) time, but the shape affects h. Repeated deletions of only successors, or only predecessors, can skew the tree over time. Balanced trees such as AVL trees add rotations after each deletion to keep h near log n.
Common errors
- Forgetting to assign the result back. Writing
delete(node.left, key)withoutnode.left = ...leaves the old pointer in place, and the node is never removed. - Deleting the successor with a plain pointer change instead of a recursive call. The successor may have a right child that must be reattached.
- Calling
deletefor the successor on the whole tree instead of the right subtree. With distinct keys this still works but does extra work. Starting atnode.rightis the correct, cheaper form. - Assuming the key exists. When the key is absent, the search reaches
Noneand returnsNone, so the tree is unchanged. This is correct behaviour and needs no special handling. - Mixing predecessor and successor in one tree without care. Either choice is valid for correctness. A GATE question usually names which one to use, so read it closely.
Deletion and inorder order
Deleting a key removes exactly that key from the inorder sequence and changes nothing else. This gives a quick check. After any deletion, run an inorder traversal and confirm the output is still sorted and lacks only the deleted key. The program above prints this after every step, so you can verify each of the three cases.
Exercise
Insert 15, 10, 20, 8, 12, 17, 25, 11 into an empty BST in that order. Delete 10 using the inorder successor. Give the new left child of the root and the inorder traversal afterwards.
Show answer
Node 10 has two children, 8 and 12. The successor is the smallest key in the right subtree rooted at 12. Going left from 12 reaches 11, which has no left child, so the successor is 11. Copy 11 into the node, then delete 11 from the right subtree, which leaves 12 with no left child. The new left child of the root is 11, with 8 on its left and 12 on its right. The inorder traversal is 8, 11, 12, 15, 17, 20, 25.
Exercise
Why is deleting a node with two children never worse than O(h), even though it involves a second deletion?
Show answer
The second deletion removes the inorder successor, which has no left child. It is a leaf or one-child case and finishes immediately. The successor lies on a downward path from the target, so the full work is one descent from the root, at most h steps, plus constant work.
Exercise
A BST has root 40 with a left child 20 and a right child 60. Node 60 has only a left child, 50. Delete 40 using the inorder predecessor. What is the root afterwards?
Show answer
The predecessor is the largest key in the left subtree rooted at 20. Node 20 has no right child, so the predecessor is 20. Copy 20 into the root and delete 20 from the left subtree, which leaves that subtree empty. The root is 20, with no left child and right child 60 (whose left child is 50).