TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › B-Trees: Definition, Height and Search

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 kk keys splits the key space into k+1k + 1 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 t≥2t \ge 2 is a rooted tree with these properties.

  1. Every node xx stores x.nx.n keys in increasing order, x.key0<x.key1<⋯<x.keyx.n−1x.\textit{key}_0 < x.\textit{key}_1 < \cdots < x.\textit{key}_{x.n - 1}, and a flag x.leafx.\textit{leaf}.
  2. An internal node has exactly x.n+1x.n + 1 children x.c0,…,x.cx.nx.c_0, \ldots, x.c_{x.n}; a leaf has none.
  3. The keys separate the children's ranges: every key in the subtree x.cix.c_i is greater than x.keyi−1x.\textit{key}_{i-1} (if i>0i > 0) and less than x.keyix.\textit{key}_i (if i<x.ni < x.n).
  4. All leaves have the same depth, the height hh of the tree.
  5. Every node other than the root has at least t−1t - 1 keys, and so an internal non-root node has at least tt children. A nonempty tree's root has at least one key.
  6. Every node has at most 2t−12t - 1 keys, and so at most 2t2t children. A node with exactly 2t−12t - 1 keys is full.

The smallest case, t=2t = 2, 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 tt in the hundreds.

text
                        [ 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 t=2t = 2: 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 kk; if it equals kk, done; otherwise descend into the child just before it.

text
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: O(h)O(h) disk reads. Inside a node it does a linear scan of up to 2t−12t - 1 keys; a binary search would make that O(lg⁡t)O(\lg t) 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.

python · try it yourself
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 kk. 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.

cpp · try it yourself
#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 t≥2t \ge 2 with n≥1n \ge 1 keys has height

h≤log⁡tn+12h \le \log_t \frac{n + 1}{2}

Proof. Count the fewest keys a B-tree of height hh can have. The root has at least 1 key, so at least 2 children. Every other internal node has at least tt children. So there are at least 2 nodes at depth 1, at least 2t2t at depth 2, and at least 2ti−12t^{i-1} at depth ii, down to depth hh. Each non-root node has at least t−1t - 1 keys, so

n≥1+(t−1)∑i=1h2ti−1=1+2(t−1)⋅th−1t−1=2th−1\begin{aligned} n &\ge 1 + (t - 1) \sum_{i=1}^{h} 2t^{i-1} \\ &= 1 + 2(t - 1) \cdot \frac{t^h - 1}{t - 1} = 2t^h - 1 \end{aligned}

and th≤(n+1)/2t^h \le (n + 1)/2 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 (2t)h+1−1(2t)^{h+1} - 1 keys. The program builds both extremes for small tt and hh and compares their key counts with the two formulas.

python · try it yourself
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 O(log⁡tn)O(\log_t n), and a search makes O(log⁡tn)O(\log_t n) disk reads and O(tlog⁡tn)O(t \log_t n) CPU work with a linear scan per node (or O(lg⁡t⋅log⁡tn)=O(lg⁡n)O(\lg t \cdot \log_t n) = O(\lg n) with binary search). With t=1000t = 1000 and n=109n = 10^9 that is at most 3 nodes read, as the previous lesson found.

Test yourself

In a B-tree with t=4t = 4, how many keys can a non-root node hold?

  1. 1 to 4
  2. 3 to 7
  3. 4 to 8
  4. 2 to 6

What is the height of a B-tree with t=2t = 2 in which every node holds exactly one key, and n=15n = 15?

  1. 1
  2. 3
  3. 4
  4. 15

Which property keeps every root-to-leaf path in a B-tree the same length?

  1. the key-separation property
  2. the minimum number of keys per node
  3. all leaves are at the same depth
  4. keys are stored in increasing order