Essential Data Structures home
B-Tree
A wide, shallow tree that keeps many keys in each node, so a search crosses few levels and each level can be read from disk in a single block.
What it is
A B-tree is a balanced search tree in which every node holds many keys, not just one. A node with k keys has k + 1 children, and the keys inside a node act as dividers: everything in the child between two keys falls between those two values. All leaves sit at the same depth, so the tree is always perfectly balanced in height.
The width of a node is set by a number called the minimum degree, t. Every node except the root holds at least t - 1 keys and at most 2t - 1 keys, and the root holds at least 1 key. With t = 2, a node holds 1 to 3 keys and 2 to 4 children, which is also called a 2-3-4 tree. With larger t, nodes hold hundreds of keys, which is the point: a node is sized to match one disk block or database page, so reading a node costs one disk read. A B-tree with a billion keys and t = 100 is only about four levels deep, so a lookup touches at most four disk blocks.
The idea was published by Rudolf Bayer and Edward McCreight in 1972, the same year Bayer published the symmetric binary B-tree that later became the red-black tree. The B in B-tree is usually read as Bayer, or balanced, or Boeing, where Bayer and McCreight worked.
How it works
Search starts at the root and walks down. Inside a node, find the first key that is greater than or equal to the value you want. If it is equal, you have found it. If it is greater, or if no such key exists, follow the child pointer just to the left of that key and repeat. At most one node per level is read, and the height is logarithmic, so a search is O(log n).
Insert also walks down, but it splits full nodes on the way, so it never has to climb back up. A node holding the maximum 2t - 1 keys is split into two nodes of t - 1 keys each, and the middle key moves up into the parent. If the root is full, it splits first and a new root is created, which is the only way the tree grows taller. Splitting on the way down keeps every node at most 2t - 1 keys and at least t - 1 keys, so no node overflows or underflows.
Delete walks down too, but it fills up thin nodes on the way. A node holding only t - 1 keys is topped up before descending into it, either by borrowing a key from a sibling or by merging two siblings and pulling a key down from the parent. That way the tree never has to climb back up to fix an underflow. Like insert, delete needs only one pass down the tree, and it runs in O(log n) time.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Search | O(log n) | O(log n) |
| Insert | O(log n) | O(log n) |
| Delete | O(log n) | O(log n) |
| Minimum / maximum | O(log n) | O(log n) |
| In-order traversal | O(n) | O(n) |
n is the number of items. The height of a B-tree with minimum degree t is at most log_t((n + 1) / 2), so the worst case for search, insert, and delete is O(log n). The log base is t rather than 2, which is why the tree stays so shallow when t is large.
When to use it, and when not to
Use a B-tree when the data lives on disk or in a database and must stay sorted, because a B-tree turns each level of the search into one block read. It is the standard shape for database indexes and file systems, and it is the right choice when the data is too large for memory and lookups must stay cheap in disk reads.
Do not use a B-tree when the data fits comfortably in memory and you only need fast lookup by key, because a hash table is faster there, with O(1) average lookup and simpler code. Do not use it when ordering does not matter and the data changes rarely, because a sorted array with binary search is simpler. Python has no built-in B-tree; its built-in dict is a hash table.
Where you meet it
B-trees run the indexes of most databases. MySQL's InnoDB engine, PostgreSQL, and SQLite all store their indexes as B-trees (or the closely related B+ tree, which keeps all values in the leaves and links the leaves together for range scans). File systems use them too: NTFS, ext4, and Apple's APFS keep directory entries and file extents in B-trees, so finding a file by name is a short walk down a shallow tree rather than a scan of the whole disk.
In Python
class BTreeNode:
def __init__(self, leaf=True):
self.keys = []
self.children = []
self.leaf = leaf
def search(self, key):
i = 0
while i < len(self.keys) and key > self.keys[i]:
i += 1
if i < len(self.keys) and key == self.keys[i]:
return True
if self.leaf:
return False
return self.children[i].search(key)
class BTree:
def __init__(self, t=2):
self.t = t # minimum degree: each node holds 1 to 3 keys
self.root = BTreeNode()
def search(self, key):
return self.root.search(key)
def insert(self, key):
root = self.root
if len(root.keys) == 2 * self.t - 1: # root is full, grow a level
new_root = BTreeNode(leaf=False)
new_root.children.append(root)
self._split_child(new_root, 0)
self.root = new_root
self._insert_nonfull(self.root, key)
def _split_child(self, parent, i):
t = self.t
full = parent.children[i]
sibling = BTreeNode(leaf=full.leaf)
sibling.keys = full.keys[t:]
if not full.leaf:
sibling.children = full.children[t:]
full.children = full.children[:t]
middle = full.keys[t - 1]
full.keys = full.keys[:t - 1]
parent.children.insert(i + 1, sibling)
parent.keys.insert(i, middle)
def _insert_nonfull(self, node, key):
if node.leaf:
node.keys.append(key)
j = len(node.keys) - 1
while j > 0 and node.keys[j] < node.keys[j - 1]:
node.keys[j], node.keys[j - 1] = node.keys[j - 1], node.keys[j]
j -= 1
else:
i = len(node.keys) - 1
while i >= 0 and key < node.keys[i]:
i -= 1
i += 1
if len(node.children[i].keys) == 2 * self.t - 1:
self._split_child(node, i)
if key > node.keys[i]:
i += 1
self._insert_nonfull(node.children[i], key)
def inorder(self, node=None, out=None):
if out is None:
out = []
if node is None:
node = self.root
for i, key in enumerate(node.keys):
if not node.leaf:
self.inorder(node.children[i], out)
out.append(key)
if not node.leaf:
self.inorder(node.children[-1], out)
return out
def height(self, node=None):
if node is None:
node = self.root
if node.leaf:
return 1
return 1 + self.height(node.children[0])
tree = BTree(t=2)
for v in [20, 40, 10, 30, 50, 5, 15, 25, 35, 45, 55, 60]:
tree.insert(v)
print(tree.inorder()) # [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60]
print(tree.search(25)) # True
print(tree.search(99)) # False
print(tree.height()) # 2, twelve keys in two levels
print(tree.root.keys) # [20, 40, 50]
In short: a B-tree packs many keys into each node, keeps all leaves at the same depth, and splits full nodes on the way down. With nodes sized to a disk block, a search of a billion keys touches only a handful of blocks, so search, insert, and delete are O(log n) in the worst case.
Sources
- B-tree, Wikipedia
- Python docs, Data Structures tutorial
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 18