Insertion and Deletion with Transplant
Queries leave a binary search tree alone. Insertion and deletion change it, and must keep the BST property intact. Insertion is easy: a new key always becomes a leaf. Deletion is the delicate operation of the whole section, because removing an inner node leaves a hole that some other node has to fill. A small helper, TRANSPLANT, which replaces one subtree by another, makes the cases short and uniform.
Insertion
Search for the new key as if it were already in the tree. The search ends at a NIL pointer, the one place where the key may be attached without violating the BST property; attach it there as a leaf.
TREE-INSERT(T, z) // z.left = z.right = NIL
1 y = NIL // y trails x: it will be z's parent
2 x = T.root
3 while x != NIL
4 y = x
5 if z.key < x.key x = x.left else x = x.right
6 z.parent = y
7 if y == NIL T.root = z // the tree was empty
8 elseif z.key < y.key y.left = z
9 else y.right = zLike a search, insertion follows one downward path: time. The order in which keys arrive determines the shape. The same seven keys can give a tree of height 2 or a path of height 6.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
z, y, x = Node(key), None, self.root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: self.root = z
elif key < y.key: y.left = z
else: y.right = z
return z
def show(x, depth=0, out=None):
"""the tree sideways: right subtree on top, one node per line"""
out = [] if out is None else out
if x is not None:
show(x.right, depth + 1, out)
out.append(" " * depth + str(x.key))
show(x.left, depth + 1, out)
return out
def height(x):
return -1 if x is None else 1 + max(height(x.left), height(x.right))
for order in [[40, 20, 60, 10, 30, 50, 70], [10, 20, 30, 40, 50, 60, 70]]:
t = BST()
for k in order:
t.insert(k)
print(f"insert {order}: height {height(t.root)}")
print("\n".join(show(t.root)))insert [40, 20, 60, 10, 30, 50, 70]: height 2
70
60
50
40
30
20
10
insert [10, 20, 30, 40, 50, 60, 70]: height 6
70
60
50
40
30
20
10
Transplant
TRANSPLANT replaces the subtree rooted at by the subtree rooted at : 's parent gets as its child in 's place, and gets 's parent. It does not touch 's children, and may be NIL.
TRANSPLANT(T, u, v)
1 if u.parent == NIL T.root = v
2 elseif u == u.parent.left u.parent.left = v
3 else u.parent.right = v
4 if v != NIL v.parent = u.parentDeletion
To delete node there are three situations.
- has no left child. Replace by its right subtree (possibly NIL, if is a leaf).
- has a left child but no right child. Replace by its left subtree.
- has two children. Its successor is the minimum of the right subtree (Successor and Predecessor), so has no left child. takes 's place: it is larger than everything in 's left subtree and smaller than everything else in 's right subtree, so the BST property survives.
- If is 's right child, transplant into 's place and hang 's left subtree under .
- Otherwise first replace by its own right subtree (which detaches ), make 's right subtree the right subtree of , and then proceed as in the previous bullet.
TREE-DELETE(T, z)
1 if z.left == NIL
2 TRANSPLANT(T, z, z.right) // case 1
3 elseif z.right == NIL
4 TRANSPLANT(T, z, z.left) // case 2
5 else y = TREE-MINIMUM(z.right) // case 3: y has no left child
6 if y != z.right
7 TRANSPLANT(T, y, y.right) // detach y
8 y.right = z.right
9 y.right.parent = y
10 TRANSPLANT(T, z, y)
11 y.left = z.left
12 y.left.parent = yEverything except TREE-MINIMUM takes constant time, so deletion is . Note that the procedure moves nodes, never keys. Copying the successor's key into and deleting the successor's node instead would be shorter, but it would invalidate any outside pointer to the successor node, and data structures built on top of the tree (iterators, augmented trees) hold such pointers.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
z, y, x = Node(key), None, self.root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: self.root = z
elif key < y.key: y.left = z
else: y.right = z
return z
def find(self, k):
x = self.root
while x is not None and x.key != k:
x = x.left if k < x.key else x.right
return x
def transplant(self, u, v):
if u.parent is None: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
if v is not None: v.parent = u.parent
def delete(self, z):
if z.left is None:
self.transplant(z, z.right); return "case 1 (no left child)"
if z.right is None:
self.transplant(z, z.left); return "case 2 (no right child)"
y = z.right
while y.left is not None: y = y.left
how = f"case 3, successor {y.key}" + (" is the right child" if y is z.right else " is deeper")
if y is not z.right:
self.transplant(y, y.right)
y.right = z.right; y.right.parent = y
self.transplant(z, y)
y.left = z.left; y.left.parent = y
return how
def show(x, depth=0, out=None):
out = [] if out is None else out
if x is not None:
show(x.right, depth + 1, out); out.append(" " * depth + str(x.key)); show(x.left, depth + 1, out)
return out
t = BST()
for k in [50, 30, 70, 20, 40, 60, 80, 35, 45, 65, 62]:
t.insert(k)
for k in [20, 60, 65, 40, 50]:
print(f"delete {k}: {t.delete(t.find(k))}")
print("\n".join(show(t.root)))delete 20: case 1 (no left child)
delete 60: case 1 (no left child)
delete 65: case 2 (no right child)
delete 40: case 3, successor 45 is the right child
delete 50: case 3, successor 62 is deeper
80
70
62
45
35
30
The five deletions cover every case. 20 is a leaf and 60 has only a right child (case 1), 65 has only a left child (case 2), 40 has two children and its successor 45 is its right child, and the root 50 has its successor 62 deep in the right subtree: 62 is first detached (its own right subtree, empty here, takes its place), then it replaces the root.
Testing the invariants
A deletion bug usually shows up as a broken parent pointer long before it shows up as a wrong answer. The test below applies 5000 random insertions and deletions to a BST and after every operation checks three things: the BST property with bounds, that every child's parent points back, and that the set of keys equals a reference Python set.
import random
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
z, y, x = Node(key), None, self.root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: self.root = z
elif key < y.key: y.left = z
else: y.right = z
def find(self, k):
x = self.root
while x is not None and x.key != k:
x = x.left if k < x.key else x.right
return x
def transplant(self, u, v):
if u.parent is None: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
if v is not None: v.parent = u.parent
def delete(self, z):
if z.left is None: self.transplant(z, z.right)
elif z.right is None: self.transplant(z, z.left)
else:
y = z.right
while y.left is not None: y = y.left
if y is not z.right:
self.transplant(y, y.right)
y.right = z.right; y.right.parent = y
self.transplant(z, y)
y.left = z.left; y.left.parent = y
def check(t):
"""returns the sorted keys; asserts BST order and parent pointers"""
out, stack, x, last = [], [], t.root, None
assert t.root is None or t.root.parent is None
while stack or x: # iterative inorder walk
while x:
for c in (x.left, x.right):
assert c is None or c.parent is x, "broken parent pointer"
stack.append(x); x = x.left
x = stack.pop()
assert last is None or last < x.key, "BST order violated"
last = x.key; out.append(x.key)
x = x.right
return out
rng = random.Random(2026)
t, ref = BST(), set()
for step in range(5000):
k = rng.randrange(200)
if k in ref and rng.random() < 0.5:
t.delete(t.find(k)); ref.remove(k)
elif k not in ref:
t.insert(k); ref.add(k)
assert check(t) == sorted(ref)
print(f"5000 operations checked; final size {len(ref)}")5000 operations checked; final size 133
In C++
The C++ version stores nodes in a std::vector with as NIL and recycles deleted slots through a free list. It runs the same kind of random test against std::set.
#include <cstdio>
#include <random>
#include <set>
#include <vector>
struct BST {
struct Node { int key = 0, left = -1, right = -1, parent = -1; };
std::vector<Node> t;
std::vector<int> free_;
int root = -1;
int find(int k) const {
int x = root;
while (x != -1 && t[x].key != k) x = k < t[x].key ? t[x].left : t[x].right;
return x;
}
void insert(int key) {
int y = -1, x = root;
while (x != -1) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
int z;
if (!free_.empty()) { z = free_.back(); free_.pop_back(); t[z] = {key, -1, -1, y}; }
else { z = static_cast<int>(t.size()); t.push_back({key, -1, -1, y}); }
if (y == -1) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
}
void transplant(int u, int v) {
int p = t[u].parent;
if (p == -1) root = v; else if (u == t[p].left) t[p].left = v; else t[p].right = v;
if (v != -1) t[v].parent = p;
}
void erase(int z) {
if (t[z].left == -1) transplant(z, t[z].right);
else if (t[z].right == -1) transplant(z, t[z].left);
else {
int y = t[z].right;
while (t[y].left != -1) y = t[y].left;
if (y != t[z].right) {
transplant(y, t[y].right);
t[y].right = t[z].right; t[t[y].right].parent = y;
}
transplant(z, y);
t[y].left = t[z].left; t[t[y].left].parent = y;
}
free_.push_back(z);
}
bool check(int x, long lo, long hi, std::vector<int>& out) const { // order, parents, inorder keys
if (x == -1) return true;
const Node& n = t[x];
if (n.key <= lo || n.key >= hi) return false;
for (int c : {n.left, n.right}) if (c != -1 && t[c].parent != x) return false;
if (!check(n.left, lo, n.key, out)) return false;
out.push_back(n.key);
return check(n.right, n.key, hi, out);
}
};
int main() {
BST b;
std::set<int> ref;
std::mt19937 rng(2026);
for (int step = 0; step < 20000; ++step) {
int k = static_cast<int>(rng() % 300);
bool del = rng() % 2 == 0;
if (ref.count(k) && del) { b.erase(b.find(k)); ref.erase(k); }
else if (!ref.count(k)) { b.insert(k); ref.insert(k); }
std::vector<int> keys;
if (!b.check(b.root, -1, 1L << 40, keys) || keys != std::vector<int>(ref.begin(), ref.end())) {
std::printf("invariant broken at step %d\n", step);
return 1;
}
}
std::printf("20000 operations checked against std::set; final size %zu, node slots used %zu\n",
ref.size(), b.t.size());
}20000 operations checked against std::set; final size 207, node slots used 227
The free list keeps the vector small: it never holds more slots than the largest number of keys present at one time.
Test yourself
Where does TREE-INSERT place a new key?
- at the root, pushing the old root down
- always as a new leaf, at the NIL pointer where a search for the key ends
- next to its successor
- in the shallowest free position
Node has two children. Which node takes its place in TREE-DELETE?
- its left child
- its parent
- its successor, the minimum of its right subtree
- the maximum of the tree
Why does TREE-DELETE move nodes instead of copying the successor's key into ?
- Moving nodes is asymptotically faster
- Outside pointers to the successor node (iterators, augmented data) would otherwise end up pointing at a node that was removed
- Copying keys breaks the BST property
- It does not matter at all
What does TRANSPLANT change?
- 's children
- the link between 's parent and , which now leads to , and 's parent pointer
- 's children
- all nodes in the subtree of