B-Trees, 2-3 Trees and B+ Trees (DSA #13)
Every data structure so far assumed memory, where a random access costs about 100 nanoseconds. On disk, a seek costs 10 milliseconds — a hundred thousand times more. When your data lives on disk, the cost that matters is not the number of comparisons but the number of disk reads, and a binary tree is a terrible choice: its height is \(\log_2 n\), so a billion rows means 30 separate disk seeks per lookup. B-trees fix this by being short and fat: each node holds hundreds of keys, so the height drops to 3–4 and a lookup costs a handful of seeks.
This chapter covers 2-3 trees, B-trees, and B+ trees — the structures underneath almost every database index and file system.
Why multi-way beats binary
A binary tree stores one key per node and has height \(\log_2 n\). A multi-way tree stores up to \(m\) keys per node and has height \(\log_m n\). For \(m = 1000\) and \(n = 10^9\):
\[ \log_2 n \approx 30 \text{ levels}, \qquad \log_{1000} n \approx 3 \text{ levels} \]
If each level is a disk read, B-trees win by an order of magnitude. The trade is more work per node (scanning keys within a node), but that work is in memory and negligible compared to a seek.
2-3 trees: the simplest multi-way tree
A 2-3 tree is a B-tree of order 3. Every node is either a 2-node (one key, two children) or a 3-node (two keys, three children), and all leaves are at the same depth.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum height=0.7cm, font=\small\bfseries, inner sep=6pt},
a/.style={->, thick}]
\node[n, fill=orange!22] (r) at (0,0) {10 \;\textbar\; 20};
\node[n, fill=blue!12] (a) at (-2.2,-1.2) {3};
\node[n, fill=blue!12] (b) at (0,-1.2) {15};
\node[n, fill=blue!12] (c) at (2.2,-1.2) {25};
\node[n, fill=green!16] (l1) at (-2.8,-2.3) {1};
\node[n, fill=green!16] (l2) at (-1.6,-2.3) {5};
\node[n, fill=green!16] (m) at (2.8,-2.3) {30};
\draw[a] (r) -- (a); \draw[a] (r) -- (b); \draw[a] (r) -- (c);
\draw[a] (a) -- (l1); \draw[a] (a) -- (l2); \draw[a] (c) -- (m);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.9) {all leaves on the same level; a 3-node splits when it overflows};
\end{tikzpicture}
Searching descends by comparing against the node’s keys. Inserting into a full 3-node splits it: the middle key rises to the parent, and the node becomes two.
# conceptual 2-3 insert: find the leaf, insert, then split while overflowing
def insert(node, key):
leaf = find_leaf(node, key)
leaf.keys.append(key); leaf.keys.sort()
while len(leaf.keys) > 2: # 3-node overflow
mid = leaf.keys[1]
left, right = Node([leaf.keys[0]]), Node([leaf.keys[2]])
if leaf.parent is None: # split the root -> grow height
root = Node([mid], [left, right])
break
parent = leaf.parent
parent.keys.append(mid); parent.keys.sort()
replace_child(parent, leaf, left, right)
leaf = parent
return root
Splitting is how B-trees grow at the root, which is why every leaf stays at the same depth. Deletion is the mirror: borrow a key from a sibling, or merge with one if borrowing is impossible.
B-trees: the general case
A B-tree of order \(m\) satisfies:
- Every node holds at most \(m - 1\) keys and \(m\) children.
- Every non-root node holds at least \(\lceil m/2 \rceil - 1\) keys (at least half full).
- Keys within a node are sorted; a child between two keys holds values in that range.
- All leaves are at the same depth.
The minimum-fill rule keeps the tree balanced and space-efficient: no node is allowed to become nearly empty. Search, insert, and delete are all \(O(\log_m n)\), with a small constant number of disk reads.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum height=0.7cm, font=\small\bfseries, inner sep=6pt},
a/.style={->, thick}]
\node[n, fill=orange!22] (r) at (0,0) {30 \;\textbar\; 60};
\node[n, fill=blue!12] (a) at (-2.6,-1.2) {10 \;\textbar\; 20};
\node[n, fill=blue!12] (b) at (0,-1.2) {40 \;\textbar\; 50};
\node[n, fill=blue!12] (c) at (2.6,-1.2) {70 \;\textbar\; 80};
\foreach \x in {-2.6,0,2.6} { \node[font=\scriptsize, anchor=north] at (\x,-1.7) {leaves \dots}; }
\draw[a] (r) -- (a); \draw[a] (r) -- (b); \draw[a] (r) -- (c);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.1) {order-$m$ node with $m-1$ keys: short and wide};
\end{tikzpicture}
B+ trees: the database favourite
A B+ tree changes the division of labour: internal nodes store only keys (for routing), and all data lives in the leaves, which are linked in a chain. This yields two wins:
- Range queries are fast. Find the lower bound, then walk the linked leaves without returning to the root.
- Higher fan-out. Internal nodes skip data pointers, so they hold more keys and the tree is even shorter.
\[ \text{B+ range scan} = O(\log_m n) \text{ to find the start} + O(k) \text{ to walk } k \text{ results} \]
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum height=0.65cm, font=\small\bfseries, inner sep=6pt},
leaf/.style={draw, thick, rounded corners=2pt, minimum height=0.65cm, font=\small\bfseries, fill=green!16, inner sep=8pt},
a/.style={->, thick}]
\node[n, fill=orange!22] (r) at (0,0) {20 \;\textbar\; 40};
\node[leaf] (l1) at (-2.6,-1.2) {5, 10, 15};
\node[leaf] (l2) at (0,-1.2) {20, 30};
\node[leaf] (l3) at (2.6,-1.2) {40, 50};
\draw[a] (r) -- (l1); \draw[a] (r) -- (l2); \draw[a] (r) -- (l3);
\draw[a, dashed] (l1) -- (l2); \draw[a, dashed] (l2) -- (l3);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.9) {leaves are linked: a range scan walks sideways, never up};
\end{tikzpicture}
Where they are used
- Database indexes. PostgreSQL, MySQL/InnoDB, SQLite, and Oracle use B+ trees for their default indexes. The primary key index in InnoDB is the table, stored in a B+ tree.
- File systems. NTFS, ext4 (via extents and HTrees), Btrfs, and APFS use B-tree variants to map filenames and block numbers.
- Key-value stores. LMDB and Berkeley DB are B-tree engines.
When you create an index on a column, you are paying to build and maintain a B+ tree whose keys are that column’s values and whose leaves point at the rows.
B-tree vs B+ tree vs LSM tree
| B-tree | B+ tree | LSM tree | |
|---|---|---|---|
| Data location | all nodes | leaves only | sorted runs + compaction |
| Range scans | okay | excellent (linked leaves) | good (merged runs) |
| Write pattern | in-place | in-place | append-only |
| Good for | general | read-heavy, ranges | write-heavy |
| Examples | file systems | DB indexes | Cassandra, RocksDB |
LSM trees (log-structured merge) are the write-optimized alternative: buffer writes in memory, flush sorted runs, and merge them in the background. They trade read amplification for write throughput and are common in write-heavy systems.
Pitfalls
- Tuning the order wrong. A node should match the disk page size (often 4–16 KB) to make one read per node. Too small and the tree is tall; too large and each read wastes I/O.
- Forgetting the minimum-fill rule. Nodes that underflow must borrow or merge, or the tree loses its balance guarantee.
- Assuming in-memory semantics. B-trees are designed around disk pages; in memory, cache behavior and CPU cost matter more.
- Ignoring write amplification. In-place B-tree updates rewrite pages; write-heavy workloads may prefer an LSM tree.
- Range scans on a plain B-tree. Without linked leaves, ranges require repeated root-to-leaf descents.
Why is a B-tree shorter than a binary search tree, and why does that matter on disk? What does a B+ tree add over a B-tree?
ASolution
A B-tree node holds many keys (\(m-1\)) and children (\(m\)), so height is \(\log_m n\) instead of \(\log_2 n\); fewer levels means fewer disk seeks, the dominant cost. A B+ tree stores data only in linked leaves, giving higher fan-out and efficient range scans by walking leaf siblings.
Next: Tries (DSA #14) — a tree keyed by characters, built for prefixes.