Skip to main content

6.10 B-Trees and B+ Trees Foundations

πŸ“šModule 06 β€’ Trees & HierarchiesTopic 6.10⏱️11 mins
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ Core Intuition: The 3-Second Mental Model​

🍳 The Everyday Analogy:​

Imagine searching for a single legal statute inside a multi-building archive. If each filing cabinet holds only one sheet of paper and two hallway signs (Left or Right), finding one record among a billion files forces you to unlock thirty separate cabinets across thirty corridors. Instead, put an entire 500-entry directory index on the front desk of each floor. One glance directs you immediately to the exact wing, shrinking thirty slow trips down to three page reads.

πŸ’» Bridging to Computer Science:​

Binary Search Trees and AVL Trees assume every pointer hop hits fast RAM in nanoseconds. On SSDs and spinning disks, fetching a single 4 KB or 16 KB page costs orders of magnitude more latency than scanning hundreds of sorted keys already loaded into cache. B-Trees and B+ Trees flatten tree height dramatically by packing hundreds of keys and child pointers into a single disk-page node, guaranteeing shallow, perfectly balanced O(log⁑mn)\mathcal{O}(\log_m n) I/O lookups.


🧱 Why High Branching Factor Conquers Disk Latency​

An AVL tree storing N=109N = 10^9 keys requires β‰ˆ30\approx 30 pointer dereferences per search. Even if only 20 levels miss RAM cache, twenty random disk seeks stall CPU execution for milliseconds.

By choosing a high order mm matched to the hardware page size (typically mβ‰ˆ200m \approx 200 to 10001000), a single disk fetch pulls in an entire sorted block of delimiter keys and child block IDs. With m=500m = 500, storing one billion records requires a tree height of at most:

hβ‰€βŒŠlog⁑250 ⁣(109+12)βŒ‹=3Β levelsh \le \left\lfloor \log_{250}\!\left(\frac{10^9 + 1}{2}\right) \right\rfloor = 3 \text{ levels}

πŸ“ Formal Properties of an Order-m B-Tree​

In classical database and algorithms literature (Knuth / CLRS), a B-Tree of order mm (maximum children per node) enforces five structural invariants so nodes never become too sparse or overflow:

  1. Maximum Children & Keys: Every node has at most mm children and therefore at most mβˆ’1m - 1 keys.
  2. Minimum Children (Non-Root Internal Nodes): Every internal node except the root must have at least ⌈m/2βŒ‰\lceil m / 2 \rceil children (i.e., at least ⌈m/2βŒ‰βˆ’1\lceil m / 2 \rceil - 1 keys).
  3. Root Exception: If the tree is non-empty, the root has at least 22 children unless it is itself a leaf node (containing 11 to mβˆ’1m - 1 keys).
  4. Uniform Leaf Depth: All leaf nodes sit at the exact same depth from the root β€” a B-Tree never grows unbalanced along one branch.
  5. Sorted Interleaving: A non-leaf node with kk keys stores k+1k + 1 child pointers P0,K1,P1,…,Kk,PkP_0, K_1, P_1, \dots, K_k, P_k, partitioning subtrees cleanly into strictly disjoint key ranges.

βš™οΈ Splitting Bottom-Up Without Increasing Skew​

Unlike a binary search tree that allocates new leaves blindly downward (risking chains), a B-Tree grows upward from the root when nodes overflow:

  1. Descend from the root to the target leaf where the new key belongs.
  2. If the leaf has fewer than mβˆ’1m - 1 keys, insert in sorted order and stop.
  3. Overflow Split: If the node already holds mβˆ’1m - 1 keys, adding the new key temporarily creates mm keys. Promote the median key up into the parent node, and split the remaining keys evenly into a left half and right half node.
  4. If promoting the median fills the parent, the split cascades upward; splitting the root creates a brand-new root with 1 key and 2 children, increasing tree height uniformly by +1+1 across all leaves simultaneously.

πŸ”— B-Trees vs. B+ Trees: Why Databases Choose B+ Trees​

Production storage engines (PostgreSQL, MySQL InnoDB, SQLite, NTFS) almost universally implement B+ Trees rather than textbook B-Trees.

Textbook B-Tree vs. Production B+ Tree

How stripping data payloads from internal nodes accelerates both point lookups and range scans

B-Tree

Keys + Payloads Everywhere

πŸ“¦
Dominant Architecture / DomainMixed Internal & Leaf Storage
  • β€’Data pointers / row records live in BOTH internal nodes and leaves.
  • β€’Point search can terminate early at an internal node.
  • β€’Payloads eat page space -> smaller fan-out -> taller trees.
  • β€’Range queries require slow back-and-forth tree traversal.
"Early termination rarely compensates for reduced branching factor."
B+ Tree

Routing Internals + Linked Leaves

πŸ”—
Dominant Architecture / DomainRDBMS Indexes & Filesystems
  • β€’Internal nodes store ONLY separator keys and child block pointers.
  • β€’Maximum fan-out packs far more branches per 16 KB page -> shorter trees.
  • β€’All keys & payloads reside at leaf level in sorted order.
  • β€’Leaves connect via sibling pointers for blazing sequential range scans.
"Uniform leaf paths plus linked leaves make WHERE BETWEEN scans O(log_m N + K)."

🏭 Real-World Production Context: Database Indexes & Filesystems​

Where Multi-Way Balanced Trees Power Storage Systems

Every modern persistent database and filesystem relies on high fan-out trees to defeat I/O bottlenecks

πŸ—„οΈ

Clustered Primary Indexes

MySQL InnoDB / PostgreSQL
  • 16 KB pages yield branching factors around m = 500 to 1200.
  • Top 2 to 3 levels stay permanently pinned in the RAM buffer pool.
πŸ’Ύ

Filesystem Directory Extents

ext4 / XFS / Btrfs / APFS
  • Maps millions of file blocks inside directories cleanly via B+ Tree extents.
  • Copy-on-Write B-Trees in Btrfs/ZFS enable instant atomic snapshots.
πŸ”

Range Scan Iterators

OLAP & Time-Series
  • Once the first leaf key is located, sibling pointers stream consecutive records sequentially.
  • Avoids touching internal nodes again for the entire range scan.
πŸ”€

Page-Level Concurrency

Latch Crabbing
  • High branching factor plus leaf-only records shrink lock contention windows.
  • B-Link Trees add right-sibling pointers inside internal levels for lock-free reads.

πŸ“ Numerical Applications & Worked Examples​

πŸ“Problem Statement: Calculating Maximum Order and Minimum Nodes in a B-Treetheorem

Suppose a disk block size is B=4096Β bytesB = 4096\text{ bytes}, each search key occupies K=12Β bytesK = 12\text{ bytes}, each record pointer takes R=8Β bytesR = 8\text{ bytes}, and each block (child) pointer takes P=4Β bytesP = 4\text{ bytes}. Calculate:

  1. The maximum order mm (maximum children) of an internal B-Tree node vs. an internal B+ Tree node.
  2. What is the minimum number of keys a non-root internal node must store in a B-Tree of order m=9m = 9?

Step-by-Step Solution:​

  1. B-Tree Internal Node Order (mm): An internal B-Tree node holds at most mm child pointers, (mβˆ’1)(m - 1) keys, and (mβˆ’1)(m - 1) record pointers:
mβ‹…P+(mβˆ’1)β‹…(K+R)≀Bm \cdot P + (m - 1) \cdot (K + R) \le B

Substituting values:

4m+(mβˆ’1)(12+8)≀4096β€…β€ŠβŸΉβ€…β€Š24mβˆ’20≀4096β€…β€ŠβŸΉβ€…β€Š24m≀4116β€…β€ŠβŸΉβ€…β€Šm=⌊171.5βŒ‹=1714m + (m - 1)(12 + 8) \le 4096 \implies 24m - 20 \le 4096 \implies 24m \le 4116 \implies m = \lfloor 171.5 \rfloor = \mathbf{171}
  1. B+ Tree Internal Node Order (mB+m_{B+}): A B+ Tree internal node omits record pointers (RR) entirely, packing only child pointers and keys:
mB+β‹…P+(mB+βˆ’1)β‹…K≀Bβ€…β€ŠβŸΉβ€…β€Š4mB++12(mB+βˆ’1)≀4096β€…β€ŠβŸΉβ€…β€Š16mB+≀4108β€…β€ŠβŸΉβ€…β€ŠmB+=256m_{B+} \cdot P + (m_{B+} - 1) \cdot K \le B \implies 4m_{B+} + 12(m_{B+} - 1) \le 4096 \implies 16m_{B+} \le 4108 \implies m_{B+} = \mathbf{256}

(Notice how removing record pointers raises branching factor from 171171 to 256256 β€” almost 50%50\% wider per disk page!)

  1. Minimum Keys for Order m=9m = 9: By invariant #2, every non-root internal node has at least ⌈m/2βŒ‰=⌈9/2βŒ‰=5\lceil m / 2 \rceil = \lceil 9 / 2 \rceil = 5 children, so minimum keys = 5βˆ’1=45 - 1 = \mathbf{4} keys.

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Can two leaves sit at different depths in a valid B-Tree?
    • Never. Because B-Trees only increase height when the root node splits upward, every single path from root to leaf has identical length.
  2. In a B+ Tree, if a key is duplicated into an internal node during a leaf split, what happens on deletion?
    • Routing keys in internal B+ Tree nodes only act as traffic signs; sometimes implementations leave deleted separator keys intact inside internal nodes as long as the leaf is removed, whereas B-Tree deletions must immediately rebalance or swap with an inorder predecessor/successor.
  3. Why choose order m≫2m \gg 2 in storage engines instead of AVL Trees?
    • Cache-line & page locality: Disk I/O reads an entire block (β‰₯4Β KB\ge 4\text{ KB}) regardless of whether 1 key or 500 keys are inside it; B-Trees amortize each seek over hundreds of comparisons in CPU L1/L2 cache.
Common Interview Traps: Architectural Trade-Offs
  • Mixing Up "Order mm" vs. "Minimum Degree tt": Textbook authors vary! Knuth defines order mm as the maximum children (⌈m/2βŒ‰\lceil m/2 \rceil min children), whereas CLRS defines minimum degree tt (min⁑\min children =t= t, max⁑\max children =2t= 2t, max keys =2tβˆ’1= 2t - 1). Always clarify your definition before writing inequalities.
  • Assuming B+ Trees Are Faster in Pure RAM: On small in-memory datasets fitting inside L1/L2 cache, scanning an array of 200 keys per node adds branch-prediction and cache-scan overhead where tight Red-Black / AVL trees or Hash Tables often winβ€”though cache-conscious small B-Trees (like Rust's BTreeMap, B=6..11B=6..11) still outperform binary trees due to cache-line utilization!
  • Forgetting Copy-Up vs. Push-Up: On a B-Tree node split, the median key is pushed up and removed from the children; on a B+ Tree leaf split, the median key is copied up into the parent while remaining inside the right leaf so no data record disappears!

πŸš€ Navigation & Next Steps​

Next up, we step away from key-comparison trees into digital radix indexing: Tries (Prefix Trees) for O(L)\mathcal{O}(L) autocomplete and IP routing.

πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.