B-trees
A search tree that is always perfectly balanced: nodes that hold several keys, splitting overfull nodes upward, growing at the root, the invariants that keep every leaf at the same depth, and why databases use them.
A binary search tree’s shape depends on the order of insertion, and the worst order, sorted, is common. CS61B’s way out starts from a simple observation: the tree gets tall because every insertion adds a new leaf below the existing ones. What if new keys never made the tree deeper at the bottom?
Overstuffing the leaves
Suppose that instead of hanging a new node under a leaf, we add the key to the leaf, so that nodes can hold several keys. The tree never gets deeper, but a leaf could grow without limit, and searching a huge leaf is slow.
So set a limit, L, on the number of keys in a node. When a node would exceed it, split it: move its middle key up into its parent, and divide the remaining keys into two nodes on either side of that key. With L = 2, adding a third key to a node splits it:
insert 30 into [10 20]:
[10 20 30] is too full, so 20 moves up:
[20]
/ \
[10] [30]
A node with k keys has k + 1 children: one for keys below the first key, one between each pair, and one above the last. Moving a key up can overfill the parent, which then splits too, and so on toward the root. If the root splits, its middle key becomes a new root above it, and only then does the tree get one level taller.
The invariants
Because height only ever grows at the top, every leaf is always at the same depth. A tree built this way, a B-tree, keeps two invariants at all times:
- All leaves are at the same depth.
- A non-leaf node with k keys has exactly k + 1 children.
Together they force balance. The tree with L = 2 (at most two keys and three children per node) is called a 2-3 tree; with L = 3 it is a 2-3-4 tree.
With N keys, every node except possibly the root has at least one key and two children, so the height is at most about log₂ N. When nodes are fuller the tree is even shorter: with L + 1 children per node, about log_(L+1) N. Either way, search and insertion take Θ(log N) time, whatever the insertion order.
A B-tree in Swift
Each node stores its keys in a sorted array and, unless it is a leaf, its children. Insertion goes down to a leaf, inserts, and on the way back up reports any split to the parent, which inserts the promoted key:
final class BTree<Key: Comparable> {
private final class Node {
var keys: [Key] = []
var children: [Node] = [] // empty for a leaf
var isLeaf: Bool { children.isEmpty }
}
private let maxKeys: Int
private var root = Node()
private(set) var count = 0
init(maxKeys: Int) {
precondition(maxKeys >= 2)
self.maxKeys = maxKeys
}
func contains(_ key: Key) -> Bool {
var node = root
while true {
let i = node.keys.firstIndex { $0 >= key } ?? node.keys.count
if i < node.keys.count && node.keys[i] == key { return true }
if node.isLeaf { return false }
node = node.children[i]
}
}
func insert(_ key: Key) {
if let (middle, right) = insert(key, into: root) {
let newRoot = Node() // the root split: grow upward
newRoot.keys = [middle]
newRoot.children = [root, right]
root = newRoot
}
}
/// Inserts into `node`’s subtree. If `node` overflows, splits it and
/// returns the key to promote and the new right sibling.
private func insert(_ key: Key, into node: Node) -> (Key, Node)? {
let i = node.keys.firstIndex { $0 >= key } ?? node.keys.count
if i < node.keys.count && node.keys[i] == key { return nil } // already there
if node.isLeaf {
node.keys.insert(key, at: i)
count += 1
} else if let (promoted, right) = insert(key, into: node.children[i]) {
node.keys.insert(promoted, at: i)
node.children.insert(right, at: i + 1)
}
guard node.keys.count > maxKeys else { return nil }
let m = node.keys.count / 2
let right = Node()
right.keys = Array(node.keys[(m + 1)...])
let middle = node.keys[m]
node.keys.removeSubrange(m...)
if !node.isLeaf {
right.children = Array(node.children[(m + 1)...])
node.children.removeSubrange((m + 1)...)
}
return (middle, right)
}
var height: Int {
var node = root
var height = 0
while !node.isLeaf {
node = node.children[0]
height += 1
}
return height
}
}
let tree = BTree<Int>(maxKeys: 2) // a 2-3 tree
for key in 1...1000 { // sorted: the worst order for a BST
tree.insert(key)
}
print(tree.count, tree.height, tree.contains(500), tree.contains(1001)) // 1000 8 true false
A thousand keys inserted in sorted order, which would make a plain BST a path
999 levels deep, make a 2-3 tree of height 8. Since every leaf is at the same
depth, height can be measured by following the leftmost path.
Searching within a node here uses a linear scan with firstIndex, which is
fine for small nodes; with large nodes, binary search within the node is
better.
What would Swift print?
var sizes: [Int] = []
var keys = 2
for _ in 0...3 {
sizes.append(keys)
keys = 3 * keys + 2
}
print(sizes)Show answer and explanation
Answer[2, 8, 26, 80]
A full 2-3 tree of height 0 is one node with two keys. A full tree one level taller is a root with two keys above three full trees, so it holds 3k + 2 keys if each subtree holds k: 2, 8, 26, 80, which is 3ʰ⁺¹ − 1. Even a tree this full grows only one level each time its size roughly triples.
Why databases use them
B-trees are used less for their balance than for their shape. When data lives on a disk or an SSD, reading one block costs far more than processing everything in it, so a tree should reach any key in as few blocks as possible. A B-tree with nodes the size of a disk block, holding hundreds of keys each, has enormous fan-out: with 500 children per node, three levels index over a hundred million keys. SQLite, PostgreSQL, and the file systems of macOS and Linux all store their indexes as B-trees (usually B+ trees, which keep all values in the leaves).
For data in memory, the next lesson shows how to get a 2-3 tree’s guarantees with ordinary binary nodes.
Put the lines in order
Put the lines in order so the program prints [[1], [3]] 2.
var keys = [1, 2, 3]print([keys, right], middle)let middle = keys[m]let right = Array(keys[(m + 1)...])keys.removeSubrange(m...)let m = keys.count / 2
Show the correct program
var keys = [1, 2, 3]
let m = keys.count / 2
let middle = keys[m]
let right = Array(keys[(m + 1)...])
keys.removeSubrange(m...)
print([keys, right], middle)Lab 38: B-trees
Q0: What would Swift print?
What would Swift print?
var root = [10, 20]
var promoted: Int? = nil
var keys = root + [30]
keys.sort()
if keys.count > 2 {
promoted = keys[1]
root = [keys[0]]
}
print(promoted!, root, keys[2])Show answer and explanation
Answer20 [10] 30
Adding 30 to the full node [10, 20] overfills it. The middle key, 20, moves up, and the node splits into [10] and [30].
Q1: Draw it
Draw the 2-3 tree after inserting 1, 2, 3, 4, 5, 6, 7 into an empty tree, one
at a time, showing each split. Then check your drawing with the lesson’s
BTree.
Show solution
1, 2: [1 2]
3: [2] the leaf [1 2 3] splits
/ \
[1] [3]
4: [2]
/ \
[1] [3 4]
5: [2 4] [3 4 5] splits, 4 moves up
/ | \
[1] [3] [5]
6: [2 4]
/ | \
[1] [3] [5 6]
7: [4] [5 6 7] splits, 6 moves up, and then the root
/ \ [2 4 6] splits, 4 moves up: height 2
[2] [6]
/ \ / \
[1] [3] [5] [7]Seven keys in sorted order give a perfect tree of height 2. Checking with the
lesson’s code: BTree(maxKeys: 2) after inserting 1 through 7 has count 7
and height 2.
Q2: Checking the invariants
Add a method checkInvariants() to BTree that verifies: every node has at
most maxKeys keys; every non-root node has at least one; each node’s keys are
sorted; a non-leaf with k keys has k + 1 children; every key in a child lies
between the parent keys around it; and all leaves are at the same depth. Then
insert random keys and check after every insertion.
Show solution
final class BTree<Key: Comparable> {
final class Node {
var keys: [Key] = []
var children: [Node] = []
var isLeaf: Bool { children.isEmpty }
}
private let maxKeys: Int
private(set) var root = Node()
init(maxKeys: Int) {
self.maxKeys = maxKeys
}
func insert(_ key: Key) {
if let (middle, right) = insert(key, into: root) {
let newRoot = Node()
newRoot.keys = [middle]
newRoot.children = [root, right]
root = newRoot
}
}
private func insert(_ key: Key, into node: Node) -> (Key, Node)? {
let i = node.keys.firstIndex { $0 >= key } ?? node.keys.count
if i < node.keys.count && node.keys[i] == key { return nil }
if node.isLeaf {
node.keys.insert(key, at: i)
} else if let (promoted, right) = insert(key, into: node.children[i]) {
node.keys.insert(promoted, at: i)
node.children.insert(right, at: i + 1)
}
guard node.keys.count > maxKeys else { return nil }
let m = node.keys.count / 2
let right = Node()
right.keys = Array(node.keys[(m + 1)...])
let middle = node.keys[m]
node.keys.removeSubrange(m...)
if !node.isLeaf {
right.children = Array(node.children[(m + 1)...])
node.children.removeSubrange((m + 1)...)
}
return (middle, right)
}
func checkInvariants() -> Bool {
var leafDepth: Int? = nil
func check(_ node: Node, depth: Int, low: Key?, high: Key?) -> Bool {
guard node.keys.count <= maxKeys, node === root || !node.keys.isEmpty else { return false }
guard zip(node.keys, node.keys.dropFirst()).allSatisfy({ $0 < $1 }) else { return false }
if let low, let first = node.keys.first, first <= low { return false }
if let high, let last = node.keys.last, last >= high { return false }
if node.isLeaf {
if leafDepth == nil { leafDepth = depth }
return leafDepth == depth
}
guard node.children.count == node.keys.count + 1 else { return false }
return node.children.indices.allSatisfy { i in
check(node.children[i], depth: depth + 1,
low: i == 0 ? low : node.keys[i - 1],
high: i == node.keys.count ? high : node.keys[i])
}
}
return check(root, depth: 0, low: nil, high: nil)
}
}
var generator = SystemRandomNumberGenerator()
for maxKeys in [2, 3, 5] {
let tree = BTree<Int>(maxKeys: maxKeys)
for _ in 0..<500 {
tree.insert(Int.random(in: 0..<1000, using: &generator))
assert(tree.checkInvariants())
}
}The key-range check is the same idea as Lesson 38’s isBST: each child must
fit between the keys on either side of it in its parent. Checking after every
insertion, for several node sizes, is a randomized test of the whole algorithm.
Q3: Height and node size
Insert the keys 1 to 100,000, in random order, into B-trees with maxKeys of 2,
3, 10, and 100, and print their heights. Compare each with log₂ N ≈ 16.6 and
with log of N in base maxKeys + 1.
Show solution
final class BTree {
private final class Node {
var keys: [Int] = []
var children: [Node] = []
var isLeaf: Bool { children.isEmpty }
}
private let maxKeys: Int
private var root = Node()
init(maxKeys: Int) { self.maxKeys = maxKeys }
func insert(_ key: Int) {
if let (middle, right) = insert(key, into: root) {
let newRoot = Node()
newRoot.keys = [middle]
newRoot.children = [root, right]
root = newRoot
}
}
private func insert(_ key: Int, into node: Node) -> (Int, Node)? {
let i = node.keys.firstIndex { $0 >= key } ?? node.keys.count
if i < node.keys.count && node.keys[i] == key { return nil }
if node.isLeaf {
node.keys.insert(key, at: i)
} else if let (promoted, right) = insert(key, into: node.children[i]) {
node.keys.insert(promoted, at: i)
node.children.insert(right, at: i + 1)
}
guard node.keys.count > maxKeys else { return nil }
let m = node.keys.count / 2
let right = Node()
right.keys = Array(node.keys[(m + 1)...])
let middle = node.keys[m]
node.keys.removeSubrange(m...)
if !node.isLeaf {
right.children = Array(node.children[(m + 1)...])
node.children.removeSubrange((m + 1)...)
}
return (middle, right)
}
var height: Int {
var node = root, height = 0
while !node.isLeaf { node = node.children[0]; height += 1 }
return height
}
}
let keys = Array(1...100_000).shuffled()
var heights: [Int] = []
for maxKeys in [2, 3, 10, 100] {
let tree = BTree(maxKeys: maxKeys)
for key in keys { tree.insert(key) }
heights.append(tree.height)
}
assert(heights[0] <= 16 && heights[3] <= 4)
assert(heights == heights.sorted(by: >))The heights come out as 13 for a 2-3 tree, 10 for a 2-3-4 tree, 5 for 10 keys per node, and 2 for 100. Bigger nodes mean a much shorter tree, at the cost of more work inside each node, which is exactly the trade databases make.
Q4: How many keys?
What are the fewest and the most keys a 2-3 tree of height h can hold? Write both as formulas and check them for h = 0 to 5.
Show solution
The fewest: every node has one key and two children, a perfect binary tree, so 2ʰ⁺¹ − 1 keys. The most: every node has two keys and three children, so there are (3ʰ⁺¹ − 1)/2 nodes holding two keys each: 3ʰ⁺¹ − 1 keys.
func pow(_ base: Int, _ exponent: Int) -> Int {
(0..<exponent).reduce(1) { acc, _ in acc * base }
}
func fewest(_ h: Int) -> Int { h == 0 ? 1 : 1 + 2 * fewest(h - 1) }
func most(_ h: Int) -> Int { h == 0 ? 2 : 2 + 3 * most(h - 1) }
for h in 0...5 {
assert(fewest(h) == pow(2, h + 1) - 1)
assert(most(h) == pow(3, h + 1) - 1)
}The recursive definitions describe the trees directly: a minimal tree is a one-key root with two minimal subtrees, and a maximal one is a two-key root with three maximal subtrees. With N keys, then, the height is between log₃(N + 1) − 1 and log₂(N + 1) − 1: Θ(log N) either way.
What’s next
B-trees are balanced but awkward to code, with nodes of different sizes. Next lesson: red-black trees, which are binary search trees that secretly are 2-3 trees.