00:00

B+ Tree Data Structure

Last updated:

A B+ tree is a variant of the B-tree that is tuned for disk-based indexes. It makes two changes: all data records (or pointers to them) are stored only in the leaf nodes, and the leaves are linked together in key order. The internal nodes contain only keys that guide the search, much like the index at the front of a book.

Because every leaf points to the next one, a range of values can be read by finding the first key and then walking along the leaves, without climbing back up the tree.

Features of B+ Tree

  • Balanced: all leaves are on the same level. Insertions and deletions split, borrow or merge nodes so that this stays true.
  • Data only in the leaves: leaf nodes hold the keys together with the records (or record pointers); every search ends at a leaf.
  • Internal nodes are pure index: they hold keys and child pointers only. A key can therefore appear twice, once as a routing key in an internal node and once in a leaf.
  • Sorted and linked leaves: keys are kept in order and the leaves form a linked list, which makes range queries and full ordered scans fast.
  • Bounded node size: for a B+ tree of order m, an internal node has at most m children, and every internal node except the root has at least ⌈m/2⌉ children, so nodes are always at least about half full.
  • High fan-out: since internal nodes store no records, many keys fit in one disk page. A node can have hundreds of children, which keeps the tree only a few levels deep.
  • Disk-oriented: few levels mean few page reads per lookup, which is why most relational databases (for example MySQL InnoDB and PostgreSQL) use B+ trees for their indexes.

The high fan-out is the main reason for the B+ tree's speed: with 100 children per node, three levels already cover about a million keys.