B-Tree Deletion
Insertion had one danger, a node that is too full, and handled it by splitting full nodes on the way down. Deletion has the opposite danger: removing a key from a node with only keys would leave it too empty. The cure is the mirror image of proactive splitting. On the way down, before entering any child, the procedure makes sure that the child has at least keys, one more than the minimum, by borrowing a key from a sibling or by merging with one. Then a key can always be removed from the node where the descent ends, and the whole deletion is again a single downward pass, with at most one step back up in the special case of internal keys.
The definitions are in B-Trees: Definition, Height and Search and the splitting in B-Tree Insertion with Proactive Splitting.
The cases
B-TREE-DELETE is called on a node that has at least keys, or is the root. Let be the position where is, or where its subtree is.
Case 1: is in , and is a leaf. Remove it. Since had at least keys (or is the root), it still has at least .
Case 2: is in , and is internal. Let be the child before and the child after it.
- 2a. If has at least keys, find 's predecessor (the largest key in 's subtree), replace by in , and delete from 's subtree.
- 2b. Otherwise, if has at least keys, do the same with the successor (the smallest key in 's subtree).
- 2c. Otherwise both have exactly keys. Merge , and into one node of keys, removing and the pointer to from , and delete from the merged node.
Case 3: is not in . It can only be in the subtree of child . If has at least keys, simply descend. If it has only , first fix it:
- 3a. If an adjacent sibling has at least keys, borrow through the parent: the separating key of moves down into , the sibling's nearest key moves up into in its place, and the sibling's nearest child pointer moves over to . It is a rotation, B-tree style.
- 3b. If both adjacent siblings have keys, merge with one of them, moving the separating key of down as the middle key of the merged node.
Then descend into the (now larger) node that contains 's range.
The root. The root is the only node allowed fewer than keys. If a merge in case 2c or 3b takes the root's last key, the root becomes empty with a single child; that child becomes the new root, and the tree's height shrinks by one. Like growth, shrinking happens only at the top, so all leaves stay at the same depth.
B-TREE-DELETE(x, k) // x is the root or has >= t keys
1 i = first index with k <= x.key[i] (or x.n)
2 if i < x.n and x.key[i] == k
3 if x.leaf: remove key i // case 1
4 elseif x.c[i].n >= t: k' = PREDECESSOR; x.key[i] = k'; B-TREE-DELETE(x.c[i], k') // 2a
5 elseif x.c[i+1].n >= t: k' = SUCCESSOR; x.key[i] = k'; B-TREE-DELETE(x.c[i+1], k') // 2b
6 else MERGE(x, i); B-TREE-DELETE(x.c[i], k) // 2c
7 elseif x.leaf: return // k is not present
8 else if x.c[i].n == t - 1
9 if a sibling of x.c[i] has >= t keys: BORROW from it // 3a
10 else MERGE x.c[i] with a sibling // 3b
11 B-TREE-DELETE(the child now covering k, k)Cost. Each level does CPU work and disk operations, and the descent visits each level once. Cases 2a and 2b go down to a leaf to find the predecessor or successor, along the same subtree the recursive call then descends, so the total is still disk operations and CPU time.
A trace
The program builds a B-tree with from fourteen keys and deletes five of them. Together the five deletions exercise every case, and the last one shrinks the tree. The tree is printed level by level after each deletion.
class BNode:
__slots__ = ("keys", "c")
def __init__(self, keys=None, c=None):
self.keys, self.c = keys or [], c or []
class BTree:
def __init__(self, t, say=print):
self.t, self.root, self.say = t, BNode(), say
def split_child(self, x, i): # insertion, from the previous lesson
t, y = self.t, x.c[i]
z = BNode(y.keys[t:], y.c[t:])
x.keys.insert(i, y.keys[t - 1]); x.c.insert(i + 1, z)
y.keys, y.c = y.keys[:t - 1], y.c[:t]
def insert(self, k):
if len(self.root.keys) == 2 * self.t - 1:
self.root = BNode([], [self.root]); self.split_child(self.root, 0)
x = self.root
while x.c:
i = 0
while i < len(x.keys) and k > x.keys[i]: i += 1
if len(x.c[i].keys) == 2 * self.t - 1:
self.split_child(x, i)
if k > x.keys[i]: i += 1
x = x.c[i]
i = 0
while i < len(x.keys) and k > x.keys[i]: i += 1
x.keys.insert(i, k)
def merge(self, x, i):
"""child i, key i of x and child i + 1 become one node"""
y, z = x.c[i], x.c[i + 1]
y.keys += [x.keys.pop(i)] + z.keys
y.c += z.c
x.c.pop(i + 1)
def delete(self, k):
self._delete(self.root, k)
if not self.root.keys and self.root.c:
self.root = self.root.c[0]
self.say(" the root is empty: its only child becomes the root (height shrinks)")
def _delete(self, x, k):
t, i = self.t, 0
while i < len(x.keys) and k > x.keys[i]: i += 1
if i < len(x.keys) and x.keys[i] == k:
if not x.c:
x.keys.pop(i)
self.say(f" case 1: remove {k} from the leaf, leaving {x.keys}")
elif len(x.c[i].keys) >= t:
p = x.c[i]
while p.c: p = p.c[-1]
self.say(f" case 2a: replace {k} by its predecessor {p.keys[-1]}, delete {p.keys[-1]} below")
x.keys[i] = p.keys[-1]
self._delete(x.c[i], p.keys[-1])
elif len(x.c[i + 1].keys) >= t:
s = x.c[i + 1]
while s.c: s = s.c[0]
self.say(f" case 2b: replace {k} by its successor {s.keys[0]}, delete {s.keys[0]} below")
x.keys[i] = s.keys[0]
self._delete(x.c[i + 1], s.keys[0])
else:
self.merge(x, i)
self.say(f" case 2c: both children are minimal; merge them around {k} into {x.c[i].keys}")
self._delete(x.c[i], k)
return
if not x.c:
return # k is not in the tree
c = x.c[i]
if len(c.keys) == t - 1:
left = x.c[i - 1] if i > 0 else None
right = x.c[i + 1] if i + 1 < len(x.c) else None
if left is not None and len(left.keys) >= t:
c.keys.insert(0, x.keys[i - 1]); x.keys[i - 1] = left.keys.pop()
if left.c: c.c.insert(0, left.c.pop())
self.say(f" case 3a: borrow from the left sibling through the parent: child is now {c.keys}")
elif right is not None and len(right.keys) >= t:
c.keys.append(x.keys[i]); x.keys[i] = right.keys.pop(0)
if right.c: c.c.append(right.c.pop(0))
self.say(f" case 3a: borrow from the right sibling through the parent: child is now {c.keys}")
else:
if right is not None: self.merge(x, i)
else: self.merge(x, i - 1); c = x.c[i - 1]
self.say(f" case 3b: merge the child with a sibling and a parent key into {c.keys}")
self._delete(c, k)
def levels(root):
out, level = [], [root]
while level:
out.append(" ".join(str(x.keys) for x in level))
level = [c for x in level for c in x.c]
return out
b = BTree(2)
for k in [4, 6, 38, 24, 11, 20, 17, 14, 34, 2, 19, 22, 37, 32]:
b.insert(k)
print("\n".join(levels(b.root)))
for k in [19, 17, 22, 34, 20]:
print(f"delete {k}:")
b.delete(k)
print("\n".join(" " + line for line in levels(b.root)))[17]
[6] [24, 37]
[2, 4] [11, 14] [19, 20, 22] [32, 34] [38]
delete 19:
case 1: remove 19 from the leaf, leaving [20, 22]
[17]
[6] [24, 37]
[2, 4] [11, 14] [20, 22] [32, 34] [38]
delete 17:
case 2b: replace 17 by its successor 20, delete 20 below
case 1: remove 20 from the leaf, leaving [22]
[20]
[6] [24, 37]
[2, 4] [11, 14] [22] [32, 34] [38]
delete 22:
case 3a: borrow from the right sibling through the parent: child is now [22, 24]
case 1: remove 22 from the leaf, leaving [24]
[20]
[6] [32, 37]
[2, 4] [11, 14] [24] [34] [38]
delete 34:
case 3b: merge the child with a sibling and a parent key into [34, 37, 38]
case 1: remove 34 from the leaf, leaving [37, 38]
[20]
[6] [32]
[2, 4] [11, 14] [24] [37, 38]
delete 20:
case 2c: both children are minimal; merge them around 20 into [6, 20, 32]
case 2a: replace 20 by its predecessor 14, delete 14 below
case 1: remove 14 from the leaf, leaving [11]
the root is empty: its only child becomes the root (height shrinks)
[6, 14, 32]
[2, 4] [11] [24] [37, 38]
Follow the last deletion. The root [20] holds the key, and both of its children have only one key, so case 2c merges them with 20 into [6, 20, 32], which empties the root. The deletion continues in the merged node: 20 is in an internal node whose left child [11, 14] has two keys, so case 2a replaces 20 by its predecessor 14 and deletes 14 from that leaf. Finally the empty root is dropped.
Testing on many inputs
The test runs random mixes of insertions and deletions on B-trees with , and , checking all properties and the key set after every operation, and counts how often each case occurred.
import random
from collections import Counter
class BNode:
__slots__ = ("keys", "c")
def __init__(self, keys=None, c=None):
self.keys, self.c = keys or [], c or []
class BTree:
def __init__(self, t, cases):
self.t, self.root, self.cases = t, BNode(), cases
def split_child(self, x, i):
t, y = self.t, x.c[i]
z = BNode(y.keys[t:], y.c[t:])
x.keys.insert(i, y.keys[t - 1]); x.c.insert(i + 1, z)
y.keys, y.c = y.keys[:t - 1], y.c[:t]
def insert(self, k):
if len(self.root.keys) == 2 * self.t - 1:
self.root = BNode([], [self.root]); self.split_child(self.root, 0)
x = self.root
while x.c:
i = 0
while i < len(x.keys) and k > x.keys[i]: i += 1
if len(x.c[i].keys) == 2 * self.t - 1:
self.split_child(x, i)
if k > x.keys[i]: i += 1
x = x.c[i]
i = 0
while i < len(x.keys) and k > x.keys[i]: i += 1
x.keys.insert(i, k)
def merge(self, x, i):
y, z = x.c[i], x.c[i + 1]
y.keys += [x.keys.pop(i)] + z.keys
y.c += z.c
x.c.pop(i + 1)
def delete(self, k):
self._delete(self.root, k)
if not self.root.keys and self.root.c:
self.root = self.root.c[0]; self.cases["root shrinks"] += 1
def _delete(self, x, k):
t, i = self.t, 0
while i < len(x.keys) and k > x.keys[i]: i += 1
if i < len(x.keys) and x.keys[i] == k:
if not x.c:
x.keys.pop(i); self.cases["1"] += 1
elif len(x.c[i].keys) >= t:
p = x.c[i]
while p.c: p = p.c[-1]
x.keys[i] = p.keys[-1]; self.cases["2a"] += 1
self._delete(x.c[i], p.keys[-1])
elif len(x.c[i + 1].keys) >= t:
s = x.c[i + 1]
while s.c: s = s.c[0]
x.keys[i] = s.keys[0]; self.cases["2b"] += 1
self._delete(x.c[i + 1], s.keys[0])
else:
self.merge(x, i); self.cases["2c"] += 1
self._delete(x.c[i], k)
return
if not x.c:
return
c = x.c[i]
if len(c.keys) == t - 1:
left = x.c[i - 1] if i > 0 else None
right = x.c[i + 1] if i + 1 < len(x.c) else None
if left is not None and len(left.keys) >= t:
c.keys.insert(0, x.keys[i - 1]); x.keys[i - 1] = left.keys.pop()
if left.c: c.c.insert(0, left.c.pop())
self.cases["3a"] += 1
elif right is not None and len(right.keys) >= t:
c.keys.append(x.keys[i]); x.keys[i] = right.keys.pop(0)
if right.c: c.c.append(right.c.pop(0))
self.cases["3a"] += 1
else:
if right is not None: self.merge(x, i)
else: self.merge(x, i - 1); c = x.c[i - 1]
self.cases["3b"] += 1
self._delete(c, k)
def check(b):
t, out, depths = b.t, [], set()
def walk(x, depth, root):
assert len(x.keys) <= 2 * t - 1 and (root or len(x.keys) >= t - 1)
if not x.c:
depths.add(depth); out.extend(x.keys); return
assert len(x.c) == len(x.keys) + 1
for i, c in enumerate(x.c):
walk(c, depth + 1, False)
if i < len(x.keys): out.append(x.keys[i])
walk(b.root, 0, True)
assert len(depths) == 1 and out == sorted(out)
return out
rng = random.Random(8)
for t in [2, 3, 4]:
cases, deletions = Counter(), 0
for trial in range(40):
b, ref = BTree(t, cases), set()
for step in range(250):
k = rng.randrange(120)
if k in ref and rng.random() < 0.6:
b.delete(k); ref.remove(k); deletions += 1
elif k not in ref:
b.insert(k); ref.add(k)
assert check(b) == sorted(ref)
print(f"t = {t}: {deletions} deletions checked; cases: " + ", ".join(f"{c} {cases[c]}" for c in ["1", "2a", "2b", "2c", "3a", "3b", "root shrinks"]))t = 2: 2712 deletions checked; cases: 1 2712, 2a 545, 2b 259, 2c 202, 3a 1555, 3b 1515, root shrinks 673
t = 3: 2656 deletions checked; cases: 1 2656, 2a 392, 2b 143, 2c 78, 3a 822, 3b 260, root shrinks 31
t = 4: 2675 deletions checked; cases: 1 2675, 2a 310, 2b 95, 2c 42, 3a 594, 3b 212, root shrinks 78
Case 1 happens once per deletion, because every deletion ends by removing a key from a leaf; the other cases are the repairs made on the way down.
In C++
The C++ version keeps nodes in a vector (merged-away nodes are simply abandoned, which keeps the code short) and runs 100,000 seeded random operations with against std::set, verifying the structure every 1000 operations.
#include <algorithm>
#include <cstdio>
#include <random>
#include <set>
#include <vector>
class BTree {
struct Node { std::vector<int> keys, c; };
std::vector<Node> n_{Node{}};
int root_ = 0, t_;
int nkeys(int x) const { return static_cast<int>(n_[x].keys.size()); }
bool leaf(int x) const { return n_[x].c.empty(); }
void split_child(int x, int i) {
int y = n_[x].c[i];
Node z;
z.keys.assign(n_[y].keys.begin() + t_, n_[y].keys.end());
if (!leaf(y)) z.c.assign(n_[y].c.begin() + t_, n_[y].c.end());
int median = n_[y].keys[t_ - 1];
n_[y].keys.resize(t_ - 1);
if (!leaf(y)) n_[y].c.resize(t_);
n_.push_back(std::move(z));
n_[x].keys.insert(n_[x].keys.begin() + i, median);
n_[x].c.insert(n_[x].c.begin() + i + 1, static_cast<int>(n_.size()) - 1);
}
void merge(int x, int i) { // c[i] + key[i] + c[i+1]
int y = n_[x].c[i], z = n_[x].c[i + 1];
n_[y].keys.push_back(n_[x].keys[i]);
n_[y].keys.insert(n_[y].keys.end(), n_[z].keys.begin(), n_[z].keys.end());
n_[y].c.insert(n_[y].c.end(), n_[z].c.begin(), n_[z].c.end());
n_[x].keys.erase(n_[x].keys.begin() + i);
n_[x].c.erase(n_[x].c.begin() + i + 1);
}
void erase_from(int x, int k) {
for (;;) {
int i = static_cast<int>(std::lower_bound(n_[x].keys.begin(), n_[x].keys.end(), k) - n_[x].keys.begin());
if (i < nkeys(x) && n_[x].keys[i] == k) {
if (leaf(x)) { n_[x].keys.erase(n_[x].keys.begin() + i); return; } // case 1
int y = n_[x].c[i], z = n_[x].c[i + 1];
if (nkeys(y) >= t_) { // case 2a
int p = y;
while (!leaf(p)) p = n_[p].c.back();
k = n_[x].keys[i] = n_[p].keys.back();
x = y;
} else if (nkeys(z) >= t_) { // case 2b
int s = z;
while (!leaf(s)) s = n_[s].c.front();
k = n_[x].keys[i] = n_[s].keys.front();
x = z;
} else { merge(x, i); x = y; } // case 2c
continue;
}
if (leaf(x)) return; // not present
int c = n_[x].c[i];
if (nkeys(c) == t_ - 1) {
int left = i > 0 ? n_[x].c[i - 1] : -1;
int right = i < nkeys(x) ? n_[x].c[i + 1] : -1;
if (left != -1 && nkeys(left) >= t_) { // case 3a, left
n_[c].keys.insert(n_[c].keys.begin(), n_[x].keys[i - 1]);
n_[x].keys[i - 1] = n_[left].keys.back(); n_[left].keys.pop_back();
if (!leaf(left)) { n_[c].c.insert(n_[c].c.begin(), n_[left].c.back()); n_[left].c.pop_back(); }
} else if (right != -1 && nkeys(right) >= t_) { // case 3a, right
n_[c].keys.push_back(n_[x].keys[i]);
n_[x].keys[i] = n_[right].keys.front(); n_[right].keys.erase(n_[right].keys.begin());
if (!leaf(right)) { n_[c].c.push_back(n_[right].c.front()); n_[right].c.erase(n_[right].c.begin()); }
} else if (right != -1) merge(x, i); // case 3b
else { merge(x, i - 1); c = left; }
}
x = c;
}
}
void walk(int x, int depth, bool root, std::vector<int>& out, std::set<int>& depths) const {
int k = nkeys(x);
if (k > 2 * t_ - 1 || (!root && k < t_ - 1)) throw "node size";
if (leaf(x)) { depths.insert(depth); out.insert(out.end(), n_[x].keys.begin(), n_[x].keys.end()); return; }
if (static_cast<int>(n_[x].c.size()) != k + 1) throw "child count";
for (int i = 0; i <= k; ++i) {
walk(n_[x].c[i], depth + 1, false, out, depths);
if (i < k) out.push_back(n_[x].keys[i]);
}
}
public:
explicit BTree(int t) : t_(t) {}
void insert(int k) {
if (nkeys(root_) == 2 * t_ - 1) {
n_.push_back(Node{{}, {root_}});
root_ = static_cast<int>(n_.size()) - 1;
split_child(root_, 0);
}
int x = root_;
while (!leaf(x)) {
int i = static_cast<int>(std::upper_bound(n_[x].keys.begin(), n_[x].keys.end(), k) - n_[x].keys.begin());
if (nkeys(n_[x].c[i]) == 2 * t_ - 1) { split_child(x, i); if (k > n_[x].keys[i]) ++i; }
x = n_[x].c[i];
}
n_[x].keys.insert(std::upper_bound(n_[x].keys.begin(), n_[x].keys.end(), k), k);
}
void erase(int k) {
erase_from(root_, k);
if (nkeys(root_) == 0 && !leaf(root_)) root_ = n_[root_].c[0]; // the tree shrinks
}
std::vector<int> verified_keys() const {
std::vector<int> out;
std::set<int> depths;
walk(root_, 0, true, out, depths);
if (depths.size() > 1) throw "leaf depths";
return out;
}
};
int main() {
BTree b(3);
std::set<int> ref;
std::mt19937 rng(8);
long inserts = 0, erases = 0;
for (int step = 1; step <= 100000; ++step) {
int k = static_cast<int>(rng() % 3000);
if (ref.count(k) && rng() % 2 == 0) { b.erase(k); ref.erase(k); ++erases; }
else if (!ref.count(k)) { b.insert(k); ref.insert(k); ++inserts; }
if (step % 1000 == 0 && b.verified_keys() != std::vector<int>(ref.begin(), ref.end())) {
std::printf("mismatch at step %d\n", step);
return 1;
}
}
std::printf("%ld inserts and %ld deletes with t = 3 agree with std::set; final size %zu\n", inserts, erases, ref.size());
}34632 inserts and 32661 deletes with t = 3 agree with std::set; final size 1971
In practice: Many databases do not merge or borrow eagerly. PostgreSQL's B-tree indexes, for example, let pages become underfull and reclaim only pages that become completely empty, because deletions are often followed by insertions into the same key range, and rebalancing would be wasted work. The guarantees of this lesson are what a textbook B-tree promises; real systems trade some of them for less I/O.
Test yourself
With , the descent is about to enter a child with 2 keys, and its left sibling has 4 keys. What happens?
- case 3b: merge the child with the sibling
- case 3a: the parent's separating key moves down into the child and the sibling's largest key moves up
- nothing: 2 keys is allowed
- the child splits
Why does deletion make sure that every child it enters has at least keys?
- So the child can be split
- So that removing a key (here or deeper) never leaves a node with fewer than keys, and no repair has to go back up
- To keep the tree perfectly full
- Because the root needs keys
When does a B-tree's height decrease?
- after every merge
- when a merge takes the last key of the root, leaving it empty with one child
- when a leaf becomes empty
- never
Key is in an internal node, and both children around it have exactly keys. What does case 2c do?
- borrows a key from a sibling
- replaces by its predecessor
- merges the two children and into one node of keys, then deletes from it
- deletes directly from the internal node