Sub topic 11
B-tree Structure, Order and Balance Rules
Assume you know arrays, linked lists, binary search, balanced search trees, logarithms, and disk blocks. This chapter uses the convention that the order of a B-tree is the maximum number of child pointers in an internal node.
What a B-tree stores
A B-tree is a height-balanced search tree designed to reduce disk block accesses. Each node usually fits in one disk block and contains sorted keys plus child pointers.
For a B-tree of order \(m\):
- An internal node has at most \(m\) child pointers.
- It therefore has at most \(m-1\) keys.
- Every non-root internal node has at least \(\lceil m/2\rceil\) child pointers.
- Every non-root node has at least \(\lceil m/2\rceil-1\) keys.
- A non-leaf root has at least two child pointers.
- All leaves occur at the same depth.
A leaf may contain records or pointers to records. Unlike a B+ tree, a B-tree may also store records in internal nodes.
For a node with keys \(K1, K2, \ldots, K_t\), its child pointers divide the key space into \(t+1\) ranges. A search compares the target with the sorted keys, chooses one range, and continues downward.
Computing the order from a block size
Let:
- \(B\) be the block size.
- \(K\) be the size of one key.
- \(P\) be the size of one child pointer.
- \(p\) be the number of child pointers.
An internal node with \(p\) pointers has \(p-1\) keys. It fits when:
\[ pP+(p-1)K \leq B \]
Rearranging gives:
\[ p \leq \left\lfloor\frac{B+K}{P+K}\right\rfloor \]
Therefore, the maximum order is:
import math
def btree_order(block_size, key_size, pointer_size):
return math.floor(
(block_size + key_size) / (key_size + pointer_size)
)
order = btree_order(512, 8, 6)
print(order) # 37
print(order - 1) # 36 maximum keys
print(math.ceil(order / 2)) # 19 minimum child pointersWith 512-byte blocks, 8-byte keys, and 6-byte pointers, the order is 37. An internal node can contain at most 36 keys and 37 pointers. A non-root internal node needs at least 19 pointers and 18 keys.
Balance during updates
During insertion, a full node temporarily overflows. The tree splits it into two nodes and promotes a separator key to the parent. If the parent is also full, the split can move upward. Splitting the root creates a new root and increases the tree height by one.
During deletion, removing a key can cause underflow. The node first tries to borrow a key through its parent from a neighboring node. If borrowing is impossible, it merges with a neighbor and pulls a separator key down from the parent.
Exercise
A B-tree has order 5. What are the maximum keys in any node and the minimum keys in a non-root node?
Show answer
The maximum is 4 keys. The minimum is ceil(5/2) - 1 = 2 keys.