Data Structures · Trees

B-trees

A B-tree is an m-way search tree with rules that keep it balanced: every node except the root is at least half full, and every leaf sits at the same depth. It is to an m-way search tree what an AVL tree is to a binary search tree. B-trees keep large sorted collections a few levels tall, which is why databases and file systems use them.

From m-way tree to B-tree

On the m-way search tree page, nodes held up to m − 1 keys and had up to m children. That cut the height, but nothing kept the tree balanced: sorted input still made a chain. A plain BST has the same problem, and the AVL tree fixed it. The B-tree fixes it for m-way trees.

binary search treeAVL treeAdds a height rule and repairs it with rotations.
m-way search treeB-treeAdds a fullness rule and an equal-depth rule, and repairs them by splitting, borrowing and merging nodes.
Plain 3-way tree, keys 1 to 12 in order. A chain six levels tall.
B-tree of order 3, same keys, same order. Three levels, and every leaf is on the bottom one.

The rules

A B-tree of order m is an m-way search tree in which:

  1. every node holds at most m − 1 keys, kept in sorted order;
  2. every node except the root holds at least ⌈m/2⌉ − 1 keys, so it is about half full or more;
  3. the root holds at least one key (unless the tree is empty);
  4. an internal node with k keys has exactly k + 1 children, with no missing gaps;
  5. every leaf is at the same depth.

Keys still guide the search as in any m-way tree: for a key k in a node, keys in the child to its left are smaller than k and keys in the child to its right are larger.

Terminology: the order m is the most children a node may have. The root is the top node, internal nodes have children, and leaves have none.

A B-tree of order 4. Every node holds 1 to 3 keys, each internal node with k keys has k + 1 children, and all leaves are on the bottom level.
Order mKeys per node (not the root)Children per internal node (not the root)
31 to 22 to 3
41 to 32 to 4
52 to 43 to 5
10049 to 9950 to 100
Stop and think
A B-tree of order 3 is often called a 2-3 tree. Why?

Every internal node has either 2 or 3 children: at most m = 3, and at least ⌈3/2⌉ = 2. Likewise an order-4 B-tree is a 2-3-4 tree.

Why does the root get an exception to the minimum?

A tree with only a few keys has to put them somewhere. With 1 key in an order-5 tree, the root holds 1 key, below the minimum of 2 that other nodes need. And when the root splits, the new root starts out with a single key.

Rule 5 says every leaf is at the same depth. Which rule from the m-way page does that make impossible?

The chain. In the plain m-way tree, a new key could start a new node one level below a full node, so one branch could grow far longer than the others. In a B-tree new nodes never appear below a leaf, so no branch can be longer than any other.

Searching

Search is exactly the m-way search, and it is close to a binary search with more than two ways at each step:

  1. Compare the key with the keys in the current node, left to right, stopping at the first key that is not smaller.
  2. If that key matches, the search is successful.
  3. Otherwise, move to the child in that gap. If the node is a leaf, the key is not in the tree.
BTreeNode* BTree::search(BTreeNode* node, int key) {
    if (node == nullptr)
        return nullptr;
    int i = 0;
    while (i < node->keys.size() && key > node->keys[i])
        i++;
    if (i < node->keys.size() && key == node->keys[i])
        return node;
    if (node->isLeaf)
        return nullptr;
    return search(node->children[i], key);
}
Stop and think
When the loop stops, i is the number of keys in the node that are smaller than the key. Why is that exactly the right child index?

Child 0 holds keys smaller than keys[0], child 1 holds keys between keys[0] and keys[1], and so on. If i keys are smaller than the target, it falls just after keys[i − 1] and before keys[i], which is child i's gap.

Inserting: split and grow upward

A new key always goes into a leaf, in sorted position. Search for it from the root to find the right leaf. If the leaf still has at most m − 1 keys, you are done.

If the leaf now has m keys, it has overflowed. Split it:

  • the middle key moves up into the parent;
  • the keys left of the middle stay in the node;
  • the keys right of the middle move to a new sibling node, just to the right.

The parent has gained a key, so it may overflow too. Repeat the split on the way up. If the root overflows, its middle key becomes a new root above it. That is the only way a B-tree gets taller, and it adds a level above every leaf at once, so all leaves stay at the same depth.

split →
Splitting an overflowed node, order 4. [10 20 30 40] has 4 keys, one more than allowed. The middle key 20 moves up; 10 stays, and 30 and 40 move to a new sibling.

Example: inserting 10, 20, 30, 40, 50, 60 into a B-tree of order 4

After 10, 20, 30: one full node.
Insert 40: the root overflows.
Split: 20 moves up to a new root.
Insert 50: it fits in the right leaf.
Insert 60: that leaf overflows, and 40 moves up.
Stop and think
A B-tree grows at the top. Why can't it just add a new level below a full leaf, the way the m-way tree did?

The new node would be one level deeper than every other leaf, breaking the equal-depth rule. It would also hold only one key, likely below the minimum. Splitting and pushing the middle key up keeps both rules: the two halves stay on the leaf level, and the tree only gets taller when the root splits.

After a split, is each half at least half full?

Yes. An overflowed node has m keys; one moves up and the other m − 1 are shared between the two halves, so each gets at least ⌊(m − 1)/2⌋ keys, which equals ⌈m/2⌉ − 1, the minimum. For order 4 that is 1 key on the left and 2 on the right.

Insert 70 into the last tree above. What happens?

70 goes into the leaf [50 60], making [50 60 70]. That is 3 keys, the most allowed in order 4, so there is no split. The next key to land in that leaf will cause one.

Try it

Each operation steps through the C++ on the right. Inserts go down to a leaf, then come back up checking each child for overflow and splitting where needed.

Presets

The tree

Output

Call stack

    What is happening

    BTree.cpp

      Stop and think
      Run the class main() (order 3: 10 20 5 6 12 30 7 17). Before each insert, predict whether it causes a split.

      10, 20, 6, 12 and 17 fit without a split. 5 overflows the root [5 10 20], so 10 moves up to a new root. 30 overflows [12 20 30], and 20 moves up. 7 overflows [5 6 7], and 6 moves up, which overflows the root [6 10 20], so 10 moves up again to a new root: one insert, two splits, and the tree is now three levels tall. The final traversal is 5 6 7 10 12 17 20 30.

      Try "Sorted 1–20" with order 3, then the same keys on the m-way page. Compare the heights.

      The B-tree has height 4 here; the plain 3-way tree is a chain of height 10. Sorted input cannot hurt a B-tree, because every split keeps the leaves level and the tree only grows at the root.

      Traverse visits child 0, key 0, child 1, key 1, …, and the last child. Why does that print the keys in sorted order?

      It is inorder traversal generalized to m ways. Everything in child i lies between keys[i − 1] and keys[i], so printing each child's keys before the key to its right produces increasing order.

      Deleting

      Deletion is more involved, because removing a key can leave a node with fewer than ⌈m/2⌉ − 1 keys: an underflow.

      1. If the key is in a leaf, remove it.
      2. If the key is in an internal node, replace it with its inorder predecessor or successor (which is always in a leaf), then delete that key from its leaf.
      3. If a node underflows, fix it by borrowing a key from a sibling that has one to spare, or by merging with a sibling when neither has a spare.
      delete 20 →
      Borrow (order 5, minimum 2 keys). Removing 20 leaves [10] with one key. Its right sibling has three, so it can spare one: 30 comes down from the parent into the short node, and 40 moves up to replace it. The order of keys is unchanged.
      delete 50 →
      Merge (order 5). Removing 50 leaves [40] short, and both siblings have only the minimum two keys. So [10 20], the parent key 30 between them, and [40] merge into one node. The parent loses a key, and if it underflows the same fix repeats one level up. If the root is left with no keys, its only child becomes the new root and the tree gets one level shorter.
      Stop and think
      Insert grows the tree only at the root. Where does delete shrink it?

      Also at the root: when a merge takes the root's last key, the merged child becomes the new root. Every leaf moves up one level at once, so leaves stay at the same depth, the mirror image of a root split.

      Height and cost

      Every internal node except the root has at least ⌈m/2⌉ children, so the number of nodes at least multiplies by ⌈m/2⌉ at each level. That makes the height at most about log⌈m/2⌉ n, and at best about logm n when nodes are full. For large m the tree is extremely flat:

      1,000,000 keysFewest levelsMost levels
      BST (balanced at best)201,000,000
      B-tree, order 31319
      B-tree, order 10034
      B-tree, order 100023

      On disk, each node is one block, so a search in an order-1000 B-tree of a million keys reads at most 3 blocks. Inside each node the work is O(m), or O(log m) with binary search, which is cheap compared with reading the block. With m treated as a constant, search, insert and delete are all O(log n), and a full traversal is O(n).

      Stop and think
      Why use a small order like 3 or 4 in memory but an order in the hundreds on disk?

      In memory, comparisons are what cost time, and a big node means many comparisons per level, so small nodes (or a balanced BST) do fine. On disk, reading a block costs far more than the comparisons inside it, so you make each node fill a whole block and get as few levels, and as few reads, as possible.

      Variations: B+ trees and B* trees

      B+ trees keep every key (and its data) in the leaves. Internal nodes hold only copies of keys as signposts for the search, so more of them fit in each block, and the leaves are linked left to right in a list. Reading a range of keys in order means finding the first one and then walking along the leaves. Most databases and file systems use B+ trees for their indexes.

      B* trees keep nodes at least two-thirds full instead of half full. When a node overflows, it first tries to pass keys to a sibling; only when both are full do the two split into three. Nodes end up fuller, so the tree uses less space and splits less often.

      Where B-trees are used

      DatabasesIndexes for looking up records by key and for range queries.
      File systemsDirectories and the maps from files to disk blocks.
      Search engines and key-value storesSorted dictionaries of terms or keys too large to keep in memory.