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

Linked lists and trees

Recursive data: a linked list as an indirect enum, a tree as a structure that holds more trees, and recursive functions whose shape follows the data.

CS61A
Linked Lists · Trees · Composing Programs 2.9
Swift book
Enumerations

Recursive functions call themselves. Recursive data contains itself: a list whose rest is a smaller list, a tree whose branches are smaller trees. When the data is recursive, the functions that process it almost write themselves, because their structure follows the data’s.

Linked lists

A linked list is either empty, or a first element followed by the rest of the list, which is itself a linked list. That sentence is the type definition:

indirect enum List {
    case empty
    case node(Int, List)
}

let numbers = List.node(1, .node(2, .node(3, .empty)))

indirect tells Swift that a case contains a value of the enum’s own type, so it must store that part by reference. Without it, a List would have to contain a whole List inside itself, forever, and the compiler rejects the definition: “recursive enum ‘List’ is not marked ‘indirect’”.

Functions that follow the data

Every function over a list handles the two cases, and the node case recurses on the rest:

indirect enum List {
    case empty
    case node(Int, List)
}

func length(_ list: List) -> Int {
    switch list {
    case .empty: 0
    case .node(_, let rest): 1 + length(rest)
    }
}

func sum(_ list: List) -> Int {
    switch list {
    case .empty: 0
    case .node(let first, let rest): first + sum(rest)
    }
}

let numbers = List.node(1, .node(2, .node(3, .empty)))
print(length(numbers), sum(numbers))   // 3 6

The recursive leap of faith from Lesson 7 applies unchanged: assume the function works on rest, and combine that with first.

What would Swift print?

indirect enum List {
    case empty
    case node(Int, List)
}
func toArray(_ list: List) -> [Int] {
    switch list {
    case .empty: []
    case .node(let first, let rest): [first] + toArray(rest)
    }
}
func map(_ list: List, _ f: (Int) -> Int) -> List {
    switch list {
    case .empty: .empty
    case .node(let first, let rest): .node(f(first), map(rest, f))
    }
}
let numbers = List.node(1, .node(2, .node(3, .empty)))
print(toArray(map(numbers) { $0 * 10 }))

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

Show answer and explanation

Answer[10, 20, 30]

map builds a new list with f applied to each element, keeping the same shape. toArray then collects the elements in order.

Linked lists make adding to the front cheap: .node(0, numbers) is a new list that shares all of numbers without copying it. Arrays are better for most everyday work; linked lists are here because they are the simplest recursive data, and the pattern carries over to trees.

Trees

A tree has a label and a list of branches, each of which is a tree. A tree with no branches is a leaf. In Swift a structure can hold an array of its own type directly:

struct Tree {
    var label: Int
    var branches: [Tree] = []

    var isLeaf: Bool { branches.isEmpty }
}

//        1
//       / \
//      2   3
//      |
//      4
let t = Tree(label: 1, branches: [
    Tree(label: 2, branches: [Tree(label: 4)]),
    Tree(label: 3),
])

branches: [Tree] = [] gives the property a default, so a leaf can be made with just Tree(label: 4).

Tree recursion over trees

A function over a tree handles the leaf, and otherwise combines the results of calling itself on every branch. map and reduce from Lesson 4 do the combining:

struct Tree {
    var label: Int
    var branches: [Tree] = []
    var isLeaf: Bool { branches.isEmpty }
}

func countLeaves(_ t: Tree) -> Int {
    t.isLeaf ? 1 : t.branches.map(countLeaves).reduce(0, +)
}

func height(_ t: Tree) -> Int {
    t.isLeaf ? 0 : 1 + t.branches.map(height).max()!
}

func sumLabels(_ t: Tree) -> Int {
    t.label + t.branches.map(sumLabels).reduce(0, +)
}

let t = Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])
print(countLeaves(t), height(t), sumLabels(t))   // 2 2 10

Passing countLeaves to map inside countLeaves looks strange at first. It is the same leap of faith: to count the leaves of this tree, count the leaves of each branch and add.

What would Swift print?

struct Tree {
    var label: Int
    var branches: [Tree] = []
}
func printTree(_ t: Tree, _ depth: Int = 0) {
    print(String(repeating: "-", count: depth) + String(t.label))
    for branch in t.branches {
        printTree(branch, depth + 1)
    }
}
printTree(Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)]))

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

Show answer and explanation

Answer1\n-2\n--4\n-3

printTree prints a label, then each branch one level deeper. The whole branch under 2, including 4, is printed before moving on to 3: the calls go down one branch completely before the next, just like cascade in Lesson 7.

Building trees

Tree-recursive computations produce trees naturally. The tree of calls from Lesson 8’s fib can be built as data, with each label equal to that Fibonacci number:

struct Tree {
    var label: Int
    var branches: [Tree] = []
}

func fibTree(_ n: Int) -> Tree {
    if n <= 1 {
        return Tree(label: n)
    }
    let left = fibTree(n - 2)
    let right = fibTree(n - 1)
    return Tree(label: left.label + right.label, branches: [left, right])
}

print(fibTree(5).label)   // 5

Put the lines in order

Put the lines in order: leaves(t) returns the labels of the leaves from left to right, and the program prints [4, 3].

  1. var branches: [Tree] = []
  2. if t.branches.isEmpty {
  3. }
  4. var label: Int
  5. print(leaves(Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])))
  6. return t.branches.flatMap(leaves)
  7. return [t.label]
  8. struct Tree {
  9. }
  10. func leaves(_ t: Tree) -> [Int] {
  11. }

Show the correct program
struct Tree {
    var label: Int
    var branches: [Tree] = []
}
func leaves(_ t: Tree) -> [Int] {
    if t.branches.isEmpty {
        return [t.label]
    }
    return t.branches.flatMap(leaves)
}
print(leaves(Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])))

flatMap is map followed by joining the resulting arrays into one.

Binary search trees

A binary search tree (BST) is a tree where every node has at most two branches, left and right, and every value in the left branch is smaller than the node’s value while every value in the right branch is larger. That rule tells you which way to go when looking for a value, so you never search both branches:

indirect enum BST {
    case empty
    case node(BST, Int, BST)

    func contains(_ value: Int) -> Bool {
        switch self {
        case .empty:
            return false
        case .node(let left, let label, let right):
            if value == label { return true }
            return value < label ? left.contains(value) : right.contains(value)
        }
    }

    func inserting(_ value: Int) -> BST {
        switch self {
        case .empty:
            return .node(.empty, value, .empty)
        case .node(let left, let label, let right):
            if value < label { return .node(left.inserting(value), label, right) }
            if value > label { return .node(left, label, right.inserting(value)) }
            return self   // already present
        }
    }

    var sorted: [Int] {
        switch self {
        case .empty: []
        case .node(let left, let label, let right): left.sorted + [label] + right.sorted
        }
    }
}

let tree = [5, 3, 8, 1, 4, 9].reduce(BST.empty) { $0.inserting($1) }
print(tree.sorted, tree.contains(4), tree.contains(6))   // [1, 3, 4, 5, 8, 9] true false

inserting returns a new tree instead of changing the old one. Because the unchanged branches are shared rather than copied, this costs only the nodes along one path. Reading the tree in order, left, label, right, gives the values sorted.

How fast contains is depends on the tree’s height. Inserting values in random order tends to give a bushy tree whose height grows like log n; inserting them already sorted gives a tree where every node has only a right branch, no better than a list.

What would Swift print?

indirect enum BST {
    case empty
    case node(BST, Int, BST)
    func inserting(_ v: Int) -> BST {
        switch self {
        case .empty: return .node(.empty, v, .empty)
        case .node(let l, let x, let r):
            return v < x ? .node(l.inserting(v), x, r) : .node(l, x, r.inserting(v))
        }
    }
    var height: Int {
        switch self {
        case .empty: 0
        case .node(let l, _, let r): 1 + max(l.height, r.height)
        }
    }
}
let bushy = [4, 2, 6, 1, 3, 5, 7].reduce(BST.empty) { $0.inserting($1) }
let stick = [1, 2, 3, 4, 5, 6, 7].reduce(BST.empty) { $0.inserting($1) }
print(bushy.height, stick.height)

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

Show answer and explanation

Answer3 7

The same seven values make a perfectly balanced tree of height 3 when the middle value comes first, and a chain of height 7 when they arrive sorted.

Lab 12: Recursive data

Q0: What would Swift print?

What would Swift print?

indirect enum List {
    case empty
    case node(Int, List)
}
func last(_ list: List) -> Int {
    switch list {
    case .empty: return -1
    case .node(let first, .empty): return first
    case .node(_, let rest): return last(rest)
    }
}
print(last(.node(1, .node(2, .node(3, .empty)))), last(.empty))

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

Show answer and explanation

Answer3 -1

The pattern .node(let first, .empty) matches a node whose rest is empty: the last one. Cases are tried in order, so that check comes before the general .node(_, let rest).

What would Swift print?

struct Tree {
    var label: Int
    var branches: [Tree] = []
}
func count(_ t: Tree) -> Int {
    1 + t.branches.map(count).reduce(0, +)
}
print(count(Tree(label: 1, branches: [Tree(label: 2), Tree(label: 3, branches: [Tree(label: 4)])])))

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

Show answer and explanation

Answer4

count counts every node: this node, plus the nodes in each branch. The tree has labels 1, 2, 3, and 4.

Q1: Build a list

Write fromArray(_:), which builds a List from an array, and toArray(_:), which does the reverse. toArray(fromArray(a)) should be a.

Show solution
indirect enum List {
    case empty
    case node(Int, List)
}

func fromArray(_ values: [Int]) -> List {
    guard let first = values.first else {
        return .empty
    }
    return .node(first, fromArray(Array(values.dropFirst())))
}

func toArray(_ list: List) -> [Int] {
    switch list {
    case .empty: []
    case .node(let first, let rest): [first] + toArray(rest)
    }
}

assert(toArray(fromArray([4, 5, 6])) == [4, 5, 6])
assert(toArray(fromArray([])) == [])

fromArray recurses on the array without its first element; toArray recurses on the list’s rest. The two definitions mirror each other.

Q2: Maximum path sum

Write maxPathSum(_:), the largest sum of labels along any path from the root down to a leaf.

func maxPathSum(_ t: Tree) -> Int {
    // your code here
}
Show solution
struct Tree {
    var label: Int
    var branches: [Tree] = []
}

func maxPathSum(_ t: Tree) -> Int {
    t.label + (t.branches.map(maxPathSum).max() ?? 0)
}

let t = Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])
assert(maxPathSum(t) == 7)              // 1 + 2 + 4
assert(maxPathSum(Tree(label: 5)) == 5)

max() of an empty array is nil, so ?? 0 covers leaves without a separate case.

Q3: Has a path

Write hasPath(_:_:), which returns true if the array of labels appears as a path starting at the root and going down through branches.

func hasPath(_ t: Tree, _ labels: [Int]) -> Bool {
    // your code here
}
Show solution
struct Tree {
    var label: Int
    var branches: [Tree] = []
}

func hasPath(_ t: Tree, _ labels: [Int]) -> Bool {
    guard let first = labels.first, first == t.label else {
        return false
    }
    if labels.count == 1 {
        return true
    }
    let rest = Array(labels.dropFirst())
    return t.branches.contains { hasPath($0, rest) }
}

let t = Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])
assert(hasPath(t, [1, 2, 4]))
assert(hasPath(t, [1, 3]))
assert(!hasPath(t, [1, 4]))
assert(!hasPath(t, [2]))
assert(!hasPath(t, []))

contains(where:), written here with a trailing closure, is true if any branch has the rest of the path. It stops at the first branch that does.

Q4: Replace a leaf

Write replaceLeaf(_:_:_:), which returns a new tree with every leaf labeled old relabeled new. Labels that are not leaves stay the same.

Show solution
struct Tree {
    var label: Int
    var branches: [Tree] = []
    var isLeaf: Bool { branches.isEmpty }
}

func leaves(_ t: Tree) -> [Int] {
    t.isLeaf ? [t.label] : t.branches.flatMap(leaves)
}

func replaceLeaf(_ t: Tree, _ old: Int, _ new: Int) -> Tree {
    if t.isLeaf {
        return Tree(label: t.label == old ? new : t.label)
    }
    return Tree(label: t.label, branches: t.branches.map { replaceLeaf($0, old, new) })
}

let t = Tree(label: 4, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])
let replaced = replaceLeaf(t, 4, 40)
assert(leaves(replaced) == [40, 3])
assert(replaced.label == 4)       // the root is not a leaf
assert(leaves(t) == [4, 3])       // the original is unchanged

The function builds a new tree instead of changing the old one. Because Tree is a structure, the original could not be changed through t anyway, which is next lesson’s topic.

Q5: A binary search tree

Using the BST enumeration from this lesson, add a computed property min, the smallest value (or nil for an empty tree), and a method count(in range: ClosedRange<Int>) that counts the values within a range, skipping branches that cannot contain any.

Show solution
indirect enum BST {
    case empty
    case node(BST, Int, BST)

    func inserting(_ value: Int) -> BST {
        switch self {
        case .empty:
            return .node(.empty, value, .empty)
        case .node(let left, let label, let right):
            if value < label { return .node(left.inserting(value), label, right) }
            if value > label { return .node(left, label, right.inserting(value)) }
            return self
        }
    }

    var min: Int? {
        switch self {
        case .empty: return nil
        case .node(let left, let label, _): return left.min ?? label
        }
    }

    func count(in range: ClosedRange<Int>) -> Int {
        switch self {
        case .empty:
            return 0
        case .node(let left, let label, let right):
            let here = range.contains(label) ? 1 : 0
            let fromLeft = label > range.lowerBound ? left.count(in: range) : 0
            let fromRight = label < range.upperBound ? right.count(in: range) : 0
            return here + fromLeft + fromRight
        }
    }
}

let tree = [50, 30, 70, 20, 40, 60, 80].reduce(BST.empty) { $0.inserting($1) }
assert(tree.min == 20)
assert(BST.empty.min == nil)
assert(tree.count(in: 35...65) == 3)   // 40, 50, 60
assert(tree.count(in: 0...100) == 7)

The smallest value is as far left as possible. When counting, a label at or below the range’s lower end means everything to its left is too small, so that branch is skipped entirely; the same goes for the right.

Q6 (optional): Every path

Write allPaths(_:) for the Tree structure, returning every path from the root to a leaf as an array of labels, left to right.

Show solution
struct Tree {
    var label: Int
    var branches: [Tree] = []
}

func allPaths(_ t: Tree) -> [[Int]] {
    if t.branches.isEmpty {
        return [[t.label]]
    }
    return t.branches.flatMap(allPaths).map { [t.label] + $0 }
}

let t = Tree(label: 1, branches: [Tree(label: 2, branches: [Tree(label: 4)]), Tree(label: 3)])
assert(allPaths(t) == [[1, 2, 4], [1, 3]])
assert(allPaths(Tree(label: 7)) == [[7]])

Every path from a branch becomes a path from the root by putting the root’s label in front.

What’s next

Next lesson: mutation, and the difference between changing a value and changing a shared object.