Sub topic 12
B-tree search, insertion with splits, and deletion
This chapter assumes you know the B-tree structure from the previous chapter. That means the order p (the maximum number of tree pointers per node), sorted keys inside nodes, and all leaves at the same level. It also assumes you can do ceiling and floor arithmetic.
The rules every operation must preserve
A B-tree of order p obeys these limits. Every insertion and deletion exists to restore them when a node breaks them.
| Node type | Minimum children | Maximum children | Minimum keys | Maximum keys |
|---|---|---|---|---|
| Root (internal) | 2 | p | 1 | p - 1 |
| Root (also a leaf) | 0 | 0 | 1 (or empty tree) | p - 1 |
| Internal, not root | ceil(p/2) | p | ceil(p/2) - 1 | p - 1 |
| Leaf, not root | 0 | 0 | ceil(p/2) - 1 | p - 1 |
All leaves stay at the same depth. The tree grows or shrinks only at the root, which is why it stays balanced.
Search
Search starts at the root and reads one node (one block access) per level.
- Read the node into memory.
- Scan or binary-search its keys. If the key is found, stop. In a B-tree the record pointer is stored in the node, so a hit at an internal node ends the search early.
- Otherwise find the first key larger than the search key at position i and follow child pointer i. If the node is a leaf, the key is absent.
The cost is at most h block accesses, where h is the number of levels. Comparing keys inside a node costs no disk access. Only the descent does.
Insertion with splits
Insertion is bottom-up:
- Search for the key. It always ends at a leaf, which is where the key belongs.
- Insert the key into that leaf in sorted position.
- If the leaf now has p keys (one too many), split it. Take the middle key and push it up into the parent. The keys left of it stay in the old node, and the keys right of it form a new node. The new node becomes the parent's child pointer just after the promoted key.
- The parent may now overflow too, so repeat step 3 upward.
- If the root splits, create a new root holding only the promoted key. This is the only way the tree gets taller.
With an even number of keys at overflow, there are two possible middles. This chapter promotes the lower of the two, which is the key at position (n - 1) // 2 counting from 0. For order 4, an overflowing node holds 4 keys, and the second key is promoted.
Worked example: order 4
Order 4 means at most 3 keys per node and at least 1 key in a non-root node. Insert 10, 20, 30, 40, 50, 60, 70, 80, 90, 100.
- 10, 20, 30 fill one node: [10 20 30].
- Insert 40: [10 20 30 40] overflows. Promote 20. Leaves are [10] and [30 40], and the root is [20].
- Insert 50, then 60: [30 40 50 60] overflows. Promote 40. Root is [20 40], leaves are [10], [30], [50 60].
- Insert 70, then 80: [50 60 70 80] overflows. Promote 60. Root is [20 40 60], which is full but legal.
- Insert 90, then 100: [70 80 90 100] overflows. Promote 80. The root would be [20 40 60 80], which overflows. Promote 40 and split the root. The new root is [40], and the tree has three levels.
Ascending insertions leave nodes about half full. This is a known weakness of plain B-tree splitting.
Code
This program implements search and insertion for any order and builds the same tree. It counts block accesses during search.
from bisect import bisect_left
class Node:
def __init__(self, leaf=True):
self.keys = []
self.children = []
self.leaf = leaf
class BTree:
def __init__(self, order):
self.order = order # max children; max keys = order - 1
self.root = Node()
def search(self, key):
node, accesses = self.root, 1
while True:
i = bisect_left(node.keys, key)
if i < len(node.keys) and node.keys[i] == key:
return True, accesses
if node.leaf:
return False, accesses
node = node.children[i]
accesses += 1
def insert(self, key):
result = self._insert(self.root, key)
if result:
median, right = result
new_root = Node(leaf=False)
new_root.keys = [median]
new_root.children = [self.root, right]
self.root = new_root
def _insert(self, node, key):
i = bisect_left(node.keys, key)
if i < len(node.keys) and node.keys[i] == key:
return None # duplicate key, ignore
if node.leaf:
node.keys.insert(i, key)
else:
result = self._insert(node.children[i], key)
if result is None:
return None
median, right = result
node.keys.insert(i, median)
node.children.insert(i + 1, right)
if len(node.keys) < self.order:
return None
mid = (len(node.keys) - 1) // 2
median = node.keys[mid]
right = Node(node.leaf)
right.keys = node.keys[mid + 1:]
node.keys = node.keys[:mid]
if not node.leaf:
right.children = node.children[mid + 1:]
node.children = node.children[:mid + 1]
return median, right
def levels(self):
out, level = [], [self.root]
while level:
out.append([n.keys for n in level])
level = [c for n in level for c in n.children]
return out
tree = BTree(order=4)
for k in range(10, 101, 10):
tree.insert(k)
for level in tree.levels():
print(level)
print(tree.search(70))
print(tree.search(75))The output is:
[[40]]
[[20], [60, 80]]
[[10], [30], [50], [70], [90, 100]]
(True, 3)
(False, 3)Deletion
Deletion must keep every non-root node at or above its minimum key count. There are two cases.
Key in an internal node. Replace it with its in-order predecessor (the largest key in the left subtree) or its in-order successor (the smallest key in the right subtree). Both of these always sit in a leaf. Then delete that copy from the leaf. This reduces every deletion to a leaf deletion.
Key in a leaf. Remove it. If the leaf still has at least the minimum number of keys, you are done. Otherwise the leaf underflows, and you fix it in this order:
- Borrow (rotate). If an adjacent sibling has more than the minimum, move that sibling's nearest key up into the parent. Move the parent's separator key down into the underflowing node.
- Merge. If no sibling can lend, combine the underflowing node, a sibling, and the separator key from the parent into one node. The parent loses a key and a child pointer, so it may underflow. Repeat the fix at the parent.
- Shrink. If the root loses its last key through a merge, the merged child becomes the new root, and the height drops by one.
Many exam questions allow a choice between left and right siblings. State your preference, which is usually to check the left sibling first.
Worked example on the tree above
- Delete 100. The leaf [90 100] becomes [90]. The minimum is 1 key, so nothing else changes.
- Delete 70 from the original tree. The leaf [70] becomes empty. The left sibling [50] is at its minimum. The right sibling [90 100] has a spare key. Borrow through the parent: 80 moves down and 90 moves up. The result is parent [60 90], leaves [50], [80], [100].
- Delete 10 from the original tree. The leaf [10] becomes empty. Its only sibling [30] is at its minimum, so merge: [20 30]. The parent [20] loses its only key and underflows. Its sibling [60 80] can lend. Rotate through the root: 40 moves down and 60 moves up. The result is root [60], left child [40] over leaves [20 30] and [50], and right child [80] over leaves [70] and [90 100].
Cost summary
| Operation | Block reads | Block writes |
|---|---|---|
| Search | at most h | none |
| Insert, no split | h | 1 |
| Insert, with splits | h | up to 2 per split level, plus a new root if needed |
| Delete, no underflow | h | 1 |
| Delete, with borrow or merge | h plus sibling reads | a few per affected level |
For n keys, the height is at most 1 + log_m((n + 1) / 2) with m = ceil(p/2). It is at least log_p(n + 1).
Common errors
- Splitting when a node is full instead of when it overflows. A node with p - 1 keys is legal.
- Forgetting that the promoted key leaves the lower level. In a B-tree it exists once, unlike a B+ tree.
- Merging without pulling the separator down from the parent.
- Ignoring the root's exception. It may hold as few as 1 key.
Exercise
An order-5 B-tree is empty. You insert 1, 2, 3, 4, 5 in that order. Promote the middle key on overflow. What does the tree look like?
Show answer
Order 5 allows at most 4 keys. Inserting 5 gives [1 2 3 4 5], which overflows. The middle key is 3. The tree has root [3] with leaves [1 2] and [4 5].
Exercise
What is the minimum number of keys in an order-5 B-tree with 3 levels, with the root counted as level 1?
Show answer
The root has 1 key and 2 children. Each level-2 node has at least ceil(5/2) = 3 children and 2 keys, so the 2 nodes hold 4 keys. Level 3 has 2 x 3 = 6 leaves with 2 keys each, giving 12 keys. The total is 1 + 4 + 12 = 17.