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

Sets, maps, and binary search trees

The set and map abstract data types, why sorted lists cannot be searched quickly, binary search trees with search, insertion, and Hibbard deletion, ordered operations, and how insertion order decides a tree’s height.

CS61B
Sets, Extends, and BSTs · Textbook Ch. 15
Swift book
Generics · Enumerations
Documentation
Set · Dictionary

Most programs need to look things up. A spelling checker asks whether a word is in its dictionary; a web server looks up a session by its token; a compiler looks up a name to find its type. The next five lessons are about the data structures that answer these questions quickly, starting with the binary search tree, which CS61B introduces by asking how to make a sorted list searchable.

Sets and maps

Two abstract data types cover almost every lookup:

  • A set holds distinct items: insert, contains, and remove.
  • A map (a dictionary, in Swift) associates each key with a value: put(key, value), get(key), containsKey, and remove. A set is a map whose values do not matter.

Swift’s Set and Dictionary are hash tables, which Lessons 48 and 49 build. They are fast but keep no order. An ordered map, one that can list its keys in sorted order and answer questions like “the largest key below 50”, needs a different structure, and that is where trees come in.

Searching a sorted list

An ArraySet from Lesson 32 takes linear time for contains. A sorted array can use binary search, taking Θ(log N), but inserting into it shifts items, which takes Θ(N). A sorted linked list inserts cheaply once the position is found, but finding it means walking from the front: binary search needs to jump to the middle, and a linked list cannot.

CS61B’s idea is to add shortcuts. Keep a reference to the middle node, and let each half keep a reference to its own middle, and so on. The result is a tree in which each node splits the keys into those smaller than it, on the left, and those larger, on the right.

Binary search trees

A binary search tree (BST) is a binary tree in which, for every node, every key in its left subtree is smaller than the node’s key, and every key in its right subtree is larger. There are no duplicate keys.

          dog
         /    \
      bag      flat
     /   \     /   \
   alf   cat elf   glut

To search, start at the root and go left or right by comparing: each comparison discards a whole subtree. To insert, search for the key; if it is not there, the search ends at an empty spot, and the new node goes there.

final class BSTMap<Key: Comparable, Value> {
    private final class Node {
        let key: Key
        var value: Value
        var left: Node?
        var right: Node?

        init(_ key: Key, _ value: Value) {
            self.key = key
            self.value = value
        }
    }

    private var root: Node?
    private(set) var count = 0

    func get(_ key: Key) -> Value? {
        var node = root
        while let current = node {
            if key < current.key {
                node = current.left
            } else if key > current.key {
                node = current.right
            } else {
                return current.value
            }
        }
        return nil
    }

    func put(_ key: Key, _ value: Value) {
        root = put(root, key, value)
    }

    /// Inserts into the subtree rooted at `node`, and returns its new root.
    private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
        guard let node else {
            count += 1
            return Node(key, value)
        }
        if key < node.key {
            node.left = put(node.left, key, value)
        } else if key > node.key {
            node.right = put(node.right, key, value)
        } else {
            node.value = value
        }
        return node
    }

    /// The keys in sorted order: an in-order traversal.
    var keys: [Key] {
        var result: [Key] = []
        func visit(_ node: Node?) {
            guard let node else { return }
            visit(node.left)
            result.append(node.key)
            visit(node.right)
        }
        visit(root)
        return result
    }
}

let ages = BSTMap<String, Int>()
for (name, age) in [("dog", 3), ("bag", 1), ("flat", 5), ("alf", 9), ("cat", 2)] {
    ages.put(name, age)
}
ages.put("dog", 4)
print(ages.get("cat")!, ages.get("dog")!, ages.get("zebra") as Any, ages.count, ages.keys)
// 2 4 nil 5 ["alf", "bag", "cat", "dog", "flat"]

The recursive put returns the new root of each subtree and reassigns it: node.left = put(node.left, …). Most calls return the node they were given, unchanged, but at the bottom the call receives nil and returns the new node, and the parent’s assignment links it in. CS61B warns against the alternative, arm’s-length recursion, which checks whether a child exists before recursing into it. Letting the call itself handle the empty case avoids a special case for the empty tree, just as Lesson 28’s sentinel did.

Listing the keys in order, left subtree, node, right subtree, visits them sorted. That ordered traversal is what a hash table cannot offer.

What would Swift print?

final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> Node {
    guard let node else { return Node(key) }
    if key < node.key { node.left = insert(node.left, key) }
    else if key > node.key { node.right = insert(node.right, key) }
    return node
}
func height(_ node: Node?) -> Int {
    guard let node else { return -1 }
    return 1 + max(height(node.left), height(node.right))
}
var a: Node? = nil
for k in [4, 2, 6, 1, 3, 5, 7] { a = insert(a, k) }
var b: Node? = nil
for k in [1, 2, 3, 4, 5, 6, 7] { b = insert(b, k) }
print(height(a), height(b))

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

Show answer and explanation

Answer2 6

The same seven keys make a perfectly balanced tree when the middle one comes first, and a path of height 6 when they arrive in sorted order: every key goes to the right of the one before.

Deleting

Removing a key has three cases, depending on the node’s children:

  1. No children: remove the node; its parent’s reference becomes nil.
  2. One child: the child takes the node’s place.
  3. Two children: the node must be replaced by a key that keeps the order intact: either the largest key in its left subtree (its predecessor) or the smallest in its right subtree (its successor). Take the successor, delete it from the right subtree (it has at most one child, since it has no left child), and put it where the removed node was.

This is Hibbard deletion. In the same recursive style as put:

private func remove(_ node: Node?, _ key: Key) -> Node? {
    guard let node else { return nil }
    if key < node.key {
        node.left = remove(node.left, key)
        return node
    }
    if key > node.key {
        node.right = remove(node.right, key)
        return node
    }
    count -= 1
    guard let left = node.left else { return node.right }    // cases 1 and 2
    guard let right = node.right else { return left }
    var successor = right                                     // case 3
    while let smaller = successor.left {
        successor = smaller
    }
    count += 1                  // the removal below is not a real removal
    successor.right = remove(right, successor.key)
    successor.left = left
    return successor
}

The successor’s key and value move to the removed node’s position by moving the successor node itself: it is first removed from the right subtree, then given the removed node’s children.

Height is everything

Every operation walks one path from the root, so each takes time proportional to the tree’s height, the length of its longest path. That height depends entirely on the order in which keys were inserted:

  • A bushy tree, like one built with the median first, has height about log₂ N. A million keys: about 20 levels.
  • A spindly tree, like one built from sorted keys, is a linked list: height N − 1.

So a BST is Θ(log N) in the best case and Θ(N) in the worst. For keys inserted in random order, the average depth of a node is about 2 ln N, around 1.39 log₂ N, so random trees are bushy. But real data is often sorted or nearly sorted: timestamps, sequential ids, words from a dictionary file. A plain BST degrades exactly on the inputs most likely to occur. The next two lessons fix that with trees that stay balanced whatever the order.

Put the lines in order

Put the lines in order so the program prints 1.

  1. }
  2. let middle = (low + high) / 2
  3. let sorted = [1, 3, 5, 7, 9]
  4. while low < high {
  5. print(low)
  6. var low = 0, high = sorted.count - 1
  7. if sorted[middle] < 3 { low = middle + 1 } else { high = middle }

Show the correct program
let sorted = [1, 3, 5, 7, 9]
var low = 0, high = sorted.count - 1
while low < high {
    let middle = (low + high) / 2
    if sorted[middle] < 3 { low = middle + 1 } else { high = middle }
}
print(low)

Lab 37: Binary search trees

Each problem uses a node class like this one:

final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}

Q0: What would Swift print?

What would Swift print?

final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> Node {
    guard let node else { return Node(key) }
    if key < node.key { node.left = insert(node.left, key) }
    else if key > node.key { node.right = insert(node.right, key) }
    return node
}
func preorder(_ node: Node?) -> [Int] {
    guard let node else { return [] }
    return [node.key] + preorder(node.left) + preorder(node.right)
}
var root: Node? = nil
for k in [5, 3, 8, 4, 1, 9] { root = insert(root, k) }
print(preorder(root))

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

Show answer and explanation

Answer[5, 3, 1, 4, 8, 9]

A pre-order traversal lists a node before its subtrees. 5 is the root; 3 and 8 are its children; 1 and 4 go under 3; 9 goes right of 8. Inserting keys in this order rebuilds the same tree, which is how BSTs are often saved.

Q1: Floor and ceiling

Write floor(_:_:), the largest key ≤ x, and ceiling(_:_:), the smallest key ≥ x, each walking a single path from the root.

Show solution
final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}

func insert(_ node: Node?, _ key: Int) -> Node {
    guard let node else { return Node(key) }
    if key < node.key { node.left = insert(node.left, key) }
    else if key > node.key { node.right = insert(node.right, key) }
    return node
}

func floor(_ root: Node?, _ x: Int) -> Int? {
    var node = root
    var best: Int? = nil
    while let current = node {
        if current.key == x { return x }
        if current.key < x {
            best = current.key        // a candidate; look for a larger one
            node = current.right
        } else {
            node = current.left
        }
    }
    return best
}

func ceiling(_ root: Node?, _ x: Int) -> Int? {
    var node = root
    var best: Int? = nil
    while let current = node {
        if current.key == x { return x }
        if current.key > x {
            best = current.key
            node = current.left
        } else {
            node = current.right
        }
    }
    return best
}

var root: Node? = nil
for k in [50, 30, 70, 20, 40, 60, 80] { root = insert(root, k) }
assert(floor(root, 45) == 40 && floor(root, 50) == 50 && floor(root, 10) == nil)
assert(ceiling(root, 45) == 50 && ceiling(root, 65) == 70 && ceiling(root, 90) == nil)

A node smaller than x is a possible floor, but a better one may lie to its right, so the search remembers it and continues right. The walk is one path, so the cost is the tree’s height.

Q2: Is it a BST?

Write isBST(_:). The obvious check, that each node is larger than its left child and smaller than its right child, is wrong: find a tree it accepts that is not a BST, then write a correct version.

Show solution
final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int, _ left: Node? = nil, _ right: Node? = nil) {
        self.key = key
        self.left = left
        self.right = right
    }
}

func naive(_ node: Node?) -> Bool {
    guard let node else { return true }
    if let left = node.left, left.key >= node.key { return false }
    if let right = node.right, right.key <= node.key { return false }
    return naive(node.left) && naive(node.right)
}

func isBST(_ node: Node?, above low: Int? = nil, below high: Int? = nil) -> Bool {
    guard let node else { return true }
    if let low, node.key <= low { return false }
    if let high, node.key >= high { return false }
    return isBST(node.left, above: low, below: node.key)
        && isBST(node.right, above: node.key, below: high)
}

//      10
//     /
//    5
//     \
//      15        15 is right of 5, but in 10's left subtree
let tricky = Node(10, Node(5, nil, Node(15)))
assert(naive(tricky) && !isBST(tricky))
assert(isBST(Node(10, Node(5, Node(1), Node(7)), Node(20))))

Every key in a left subtree must be smaller than every ancestor it hangs to the left of, not just its parent. Passing down the allowed range, narrowed at each step, checks exactly that, in one pass.

Q3: Random versus sorted

Build BSTs of 10,000 keys inserted in sorted order and in random order, and compare their heights with log₂ 10,000 ≈ 13.3. Write insert and height iteratively, since the sorted tree is 10,000 levels deep.

Show solution
final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}

func build(_ keys: [Int]) -> Node? {
    var root: Node? = nil
    for key in keys {
        guard let start = root else { root = Node(key); continue }
        var node = start
        while true {
            if key < node.key {
                if let left = node.left { node = left } else { node.left = Node(key); break }
            } else {
                if let right = node.right { node = right } else { node.right = Node(key); break }
            }
        }
    }
    return root
}

func height(_ root: Node?) -> Int {
    guard let root else { return -1 }
    var level = [root]
    var height = -1
    while !level.isEmpty {
        height += 1
        level = level.flatMap { [$0.left, $0.right].compactMap { $0 } }
    }
    return height
}

let n = 10_000
let spindly = build(Array(0..<n))
let bushy = build(Array(0..<n).shuffled())
assert(height(spindly) == n - 1)
assert(height(bushy) < 45)       // typically about 30

height goes level by level, a breadth-first traversal (Lesson 43), which needs no recursion. The random tree is typically about 30 levels deep, a small multiple of log₂ N, while the sorted one is a 10,000-node path.

Q4: Keys in a range

Write keys(in:) for a BST, returning the keys in a closed range in sorted order, visiting only the subtrees that can contain keys in the range.

Show solution
final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}

func insert(_ node: Node?, _ key: Int) -> Node {
    guard let node else { return Node(key) }
    if key < node.key { node.left = insert(node.left, key) }
    else if key > node.key { node.right = insert(node.right, key) }
    return node
}

var visited = 0

func keys(in range: ClosedRange<Int>, _ node: Node?) -> [Int] {
    guard let node else { return [] }
    visited += 1
    var result: [Int] = []
    if range.lowerBound < node.key {
        result += keys(in: range, node.left)
    }
    if range.contains(node.key) {
        result.append(node.key)
    }
    if range.upperBound > node.key {
        result += keys(in: range, node.right)
    }
    return result
}

var root: Node? = nil
for k in [50, 30, 70, 20, 40, 60, 80, 10, 25, 65] { root = insert(root, k) }
assert(keys(in: 22...62, root) == [25, 30, 40, 50, 60])
visited = 0
_ = keys(in: 75...100, root)
assert(visited == 3)        // 50, 70, 80: the left side is never entered

The left subtree can only hold keys in range if the range starts below the node’s key, and similarly on the right. The cost is the height plus the number of keys reported, rather than the size of the tree.

Q5 (optional): A balanced tree from sorted keys

Given sorted, distinct keys, build the BST of minimum height: the median at the root, and each half built the same way. Check that 1,023 keys make a tree of height 9.

Show solution
final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    init(_ key: Int) { self.key = key }
}

func balanced(_ keys: ArraySlice<Int>) -> Node? {
    guard !keys.isEmpty else { return nil }
    let middle = keys.startIndex + keys.count / 2
    let node = Node(keys[middle])
    node.left = balanced(keys[..<middle])
    node.right = balanced(keys[(middle + 1)...])
    return node
}

func height(_ node: Node?) -> Int {
    guard let node else { return -1 }
    return 1 + max(height(node.left), height(node.right))
}

func inorder(_ node: Node?) -> [Int] {
    guard let node else { return [] }
    return inorder(node.left) + [node.key] + inorder(node.right)
}

let keys = Array(1...1023)
let root = balanced(keys[...])
assert(height(root) == 9 && inorder(root) == keys)

2¹⁰ − 1 = 1,023 keys fill a perfect tree of ten levels, height 9. This only works when all the keys are known in advance; a tree that must stay balanced while keys arrive one by one needs the ideas in the next two lessons.

What’s next

Next lesson: B-trees, which stay perfectly balanced by growing at the root rather than at the leaves.