B-Trees: Definition, Height and Search
A B-tree is a balanced search tree whose nodes hold many keys and have many children, sized so that one node fills one page of storage (Disks, Pages and the Case for B-Trees). It generalises the BST: a node with keys splits the key space into ranges, one per child. Its balance rule is simpler than the red-black colours: all leaves are at the same depth, and nodes are never too empty or too full.
The definition
A B-tree of minimum degree is a rooted tree with these properties.
- Every node stores keys in increasing order, , and a flag .
- An internal node has exactly children ; a leaf has none.
- The keys separate the children's ranges: every key in the subtree is greater than (if ) and less than (if ).
- All leaves have the same depth, the height of the tree.
- Every node other than the root has at least keys, and so an internal non-root node has at least children. A nonempty tree's root has at least one key.
- Every node has at most keys, and so at most children. A node with exactly keys is full.
The smallest case, , allows 1 to 3 keys and 2 to 4 children per internal node: the 2-3-4 tree, which is closely related to red-black trees (a black node with its red children is one 2-3-4 node). Real B-trees use in the hundreds.
[ 30 60 ]
/ | \
[10 20] [40 50 55] [70 80]
/ | \ / | | \ / | \
[3 7] [12] [22 25] [33] [42] [52] [57 58] [65] [75] [85 90]This is a valid B-tree with : every node has 1 to 3 keys, every internal node one more child than keys, all ten leaves at depth 2, and each key range is respected (the subtree between 30 and 60 holds 33 to 58).
Searching
Search is the natural generalisation of TREE-SEARCH: inside a node, find the first key that is at least ; if it equals , done; otherwise descend into the child just before it.
B-TREE-SEARCH(x, k) // returns (node, index) or NIL
1 i = 0
2 while i < x.n and k > x.key[i]
3 i = i + 1
4 if i < x.n and k == x.key[i]
5 return (x, i)
6 elseif x.leaf
7 return NIL
8 else DISK-READ(x.c[i])
9 return B-TREE-SEARCH(x.c[i], k)The search reads one node per level: disk reads. Inside a node it does a linear scan of up to keys; a binary search would make that comparisons, but either way the CPU cost per node is small next to the page read.
The program writes the tree above as nested lists, checks all six properties, and traces three searches, counting the nodes read.
def node(keys, children=()):
return {"keys": list(keys), "c": list(children)}
L = node
tree = node([30, 60], [
node([10, 20], [L([3, 7]), L([12]), L([22, 25])]),
node([40, 50, 55], [L([33]), L([42]), L([52]), L([57, 58])]),
node([70, 80], [L([65]), L([75]), L([85, 90])]),
])
def check(x, t, lo=None, hi=None, depth=0, is_root=True, leaf_depths=None):
"""asserts the B-tree properties; returns the set of leaf depths"""
leaf_depths = set() if leaf_depths is None else leaf_depths
k = x["keys"]
assert k == sorted(k) and len(set(k)) == len(k), "keys in order"
assert all((lo is None or lo < key) and (hi is None or key < hi) for key in k), "key ranges"
assert len(k) <= 2 * t - 1, "too full"
assert len(k) >= (1 if is_root else t - 1), "too empty"
if not x["c"]:
leaf_depths.add(depth)
else:
assert len(x["c"]) == len(k) + 1, "children = keys + 1"
bounds = [lo] + k + [hi]
for i, child in enumerate(x["c"]):
check(child, t, bounds[i], bounds[i + 1], depth + 1, False, leaf_depths)
if is_root:
assert len(leaf_depths) == 1, "all leaves at the same depth"
return leaf_depths
def search(x, k, trace):
trace.append(x["keys"]) # one DISK-READ per node visited
i = 0
while i < len(x["keys"]) and k > x["keys"][i]:
i += 1
if i < len(x["keys"]) and x["keys"][i] == k:
return True
return False if not x["c"] else search(x["c"][i], k, trace)
print("valid B-tree with t = 2, height", check(tree, 2).pop())
for k in [52, 25, 61]:
trace = []
found = search(tree, k, trace)
print(f"search {k}: {'found' if found else 'not found'} after reading {len(trace)} nodes: {trace}")valid B-tree with t = 2, height 2
search 52: found after reading 3 nodes: [[30, 60], [40, 50, 55], [52]]
search 25: found after reading 3 nodes: [[30, 60], [10, 20], [22, 25]]
search 61: not found after reading 3 nodes: [[30, 60], [70, 80], [65]]
In C++
In C++ a node is a struct with two vectors; inside a node, std::lower_bound does the binary search for the first key not less than . The program builds the same tree and searches for every integer from 0 to 99, checking the answers against a sorted list of the keys.
#include <algorithm>
#include <cstdio>
#include <memory>
#include <vector>
struct BNode {
std::vector<int> keys;
std::vector<std::unique_ptr<BNode>> c; // empty for a leaf
bool leaf() const { return c.empty(); }
};
std::unique_ptr<BNode> make(std::vector<int> keys, std::vector<std::unique_ptr<BNode>> kids = {}) {
auto x = std::make_unique<BNode>();
x->keys = std::move(keys);
x->c = std::move(kids);
return x;
}
template <typename... T>
std::vector<std::unique_ptr<BNode>> kids(T&&... xs) {
std::vector<std::unique_ptr<BNode>> v;
(v.push_back(std::forward<T>(xs)), ...);
return v;
}
bool search(const BNode* x, int k, int& reads) {
for (;;) {
++reads; // DISK-READ(x)
auto it = std::lower_bound(x->keys.begin(), x->keys.end(), k);
if (it != x->keys.end() && *it == k) return true;
if (x->leaf()) return false;
x = x->c[it - x->keys.begin()].get();
}
}
int main() {
auto root = make({30, 60}, kids(
make({10, 20}, kids(make({3, 7}), make({12}), make({22, 25}))),
make({40, 50, 55}, kids(make({33}), make({42}), make({52}), make({57, 58}))),
make({70, 80}, kids(make({65}), make({75}), make({85, 90})))));
std::vector<int> all = {3, 7, 10, 12, 20, 22, 25, 30, 33, 40, 42, 50, 52, 55, 57, 58, 60, 65, 70, 75, 80, 85, 90};
int found = 0, wrong = 0, total_reads = 0;
for (int k = 0; k < 100; ++k) {
int reads = 0;
bool hit = search(root.get(), k, reads);
found += hit;
wrong += hit != std::binary_search(all.begin(), all.end(), k);
total_reads += reads;
}
std::printf("100 searches: %d found, %d wrong, %.2f node reads per search (height + 1 = 3)\n",
found, wrong, total_reads / 100.0);
}100 searches: 23 found, 0 wrong, 2.89 node reads per search (height + 1 = 3)
Successful searches that end in an inner node read fewer than three nodes, which is why the average is a little below 3.
The height bound
Theorem. A B-tree of minimum degree with keys has height
Proof. Count the fewest keys a B-tree of height can have. The root has at least 1 key, so at least 2 children. Every other internal node has at least children. So there are at least 2 nodes at depth 1, at least at depth 2, and at least at depth , down to depth . Each non-root node has at least keys, so
and gives the claim. The tree that achieves the minimum, every node as empty as allowed, shows the bound is exact; at the other extreme a tree whose nodes are all full has keys. The program builds both extremes for small and and compares their key counts with the two formulas.
import math
def build(t, h, full, is_root=True):
"""the emptiest (full=False) or fullest B-tree of height h, with keys 0, 1, 2, ..."""
counter = iter(range(10 ** 9))
def make(level, root):
k = (2 * t - 1) if full else (1 if root else t - 1)
if level == h:
return {"keys": [next(counter) for _ in range(k)], "c": []}
node = {"keys": [], "c": []}
for i in range(k + 1): # inorder numbering: child, key, child, ...
node["c"].append(make(level + 1, False))
if i < k:
node["keys"].append(next(counter))
return node
return make(0, True)
def count(x):
return len(x["keys"]) + sum(count(c) for c in x["c"])
def height(x):
return 0 if not x["c"] else 1 + height(x["c"][0])
for t in [2, 3, 5]:
for h in [1, 2, 3]:
lo, hi = build(t, h, False), build(t, h, True)
assert height(lo) == height(hi) == h
n_min, n_max = count(lo), count(hi)
assert n_min == 2 * t ** h - 1 and n_max == (2 * t) ** (h + 1) - 1
assert h <= math.log((n_min + 1) / 2, t) + 1e-9 # the bound, tight at n_min
print(f"t = {t}, h = {h}: fewest keys {n_min:5} = 2t^h - 1, most keys {n_max:6} = (2t)^(h+1) - 1")t = 2, h = 1: fewest keys 3 = 2t^h - 1, most keys 15 = (2t)^(h+1) - 1
t = 2, h = 2: fewest keys 7 = 2t^h - 1, most keys 63 = (2t)^(h+1) - 1
t = 2, h = 3: fewest keys 15 = 2t^h - 1, most keys 255 = (2t)^(h+1) - 1
t = 3, h = 1: fewest keys 5 = 2t^h - 1, most keys 35 = (2t)^(h+1) - 1
t = 3, h = 2: fewest keys 17 = 2t^h - 1, most keys 215 = (2t)^(h+1) - 1
t = 3, h = 3: fewest keys 53 = 2t^h - 1, most keys 1295 = (2t)^(h+1) - 1
t = 5, h = 1: fewest keys 9 = 2t^h - 1, most keys 99 = (2t)^(h+1) - 1
t = 5, h = 2: fewest keys 49 = 2t^h - 1, most keys 999 = (2t)^(h+1) - 1
t = 5, h = 3: fewest keys 249 = 2t^h - 1, most keys 9999 = (2t)^(h+1) - 1
So a B-tree's height is , and a search makes disk reads and CPU work with a linear scan per node (or with binary search). With and that is at most 3 nodes read, as the previous lesson found.
Test yourself
In a B-tree with , how many keys can a non-root node hold?
- 1 to 4
- 3 to 7
- 4 to 8
- 2 to 6
What is the height of a B-tree with in which every node holds exactly one key, and ?
- 1
- 3
- 4
- 15
Which property keeps every root-to-leaf path in a B-tree the same length?
- the key-separation property
- the minimum number of keys per node
- all leaves are at the same depth
- keys are stored in increasing order