Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

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.

CS61B
B-Trees · Textbook Ch. 16
Swift book
Generics

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:

  1. All leaves are at the same depth.
  2. 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)

Type Error if running it would crash. For several lines of output, put each on its own line.

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.

  1. var keys = [1, 2, 3]
  2. print([keys, right], middle)
  3. let middle = keys[m]
  4. let right = Array(keys[(m + 1)...])
  5. keys.removeSubrange(m...)
  6. 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])

Type Error if running it would crash. For several lines of output, put each on its own line.

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.