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

Tree and graph traversals

Visiting every node: pre-, in-, post-, and level-order tree traversals, graphs and their vocabulary, a zoo of graph problems, depth-first search with marking and paths, and breadth-first search for fewest edges.

CS61B
Tree and Graph Traversals · Textbook Ch. 19
Swift book
Nested Types

Many questions about a structure come down to visiting every part of it in some order: printing a tree, copying a file system, finding everything reachable from one place. This lesson starts with the orders for trees, then turns to graphs, which describe any network of connections, and to the two fundamental ways of exploring them.

Tree traversals

There are four standard orders for visiting the nodes of a tree:

  • Pre-order: a node, then each of its subtrees. Copying a tree, or printing a file system with folders before their contents, uses this order.
  • In-order (binary trees only): the left subtree, the node, the right subtree. For a search tree, this is sorted order.
  • Post-order: each subtree, then the node. Computing a folder’s total size needs its contents’ sizes first, so it is post-order.
  • Level order: the root, then all nodes at depth 1, then depth 2, and so on.
indirect enum Tree {
    case empty
    case node(Tree, String, Tree)
}

func preorder(_ t: Tree) -> [String] {
    guard case .node(let l, let v, let r) = t else { return [] }
    return [v] + preorder(l) + preorder(r)
}

func inorder(_ t: Tree) -> [String] {
    guard case .node(let l, let v, let r) = t else { return [] }
    return inorder(l) + [v] + inorder(r)
}

func postorder(_ t: Tree) -> [String] {
    guard case .node(let l, let v, let r) = t else { return [] }
    return postorder(l) + postorder(r) + [v]
}

func levelOrder(_ t: Tree) -> [String] {
    var result: [String] = []
    var level = [t]
    while !level.isEmpty {
        var next: [Tree] = []
        for case .node(let l, let v, let r) in level {
            result.append(v)
            next += [l, r]
        }
        level = next
    }
    return result
}

//        D
//      /   \
//     B     F
//    / \   / \
//   A   C E   G
let leaf = { (v: String) in Tree.node(.empty, v, .empty) }
let tree = Tree.node(.node(leaf("A"), "B", leaf("C")), "D", .node(leaf("E"), "F", leaf("G")))
print(preorder(tree).joined(), inorder(tree).joined(), postorder(tree).joined(), levelOrder(tree).joined())
// DBACFEG ABCDEFG ACBEGFD DBFACEG

The first three differ only in when a node is visited relative to its subtrees; the recursion is the same. Level order is different in kind: it goes across before going down, and it needs to remember a whole level at a time. That difference, down first or across first, is exactly the difference between the two graph searches below.

Graphs

A graph is a set of vertices (nodes) and a set of edges, each connecting two vertices. Trees are graphs, but graphs in general can have cycles, several paths between two vertices, and pieces that are not connected at all. The vocabulary:

  • In an undirected graph, an edge goes both ways; in a directed graph, each edge has a direction, from one vertex to another.
  • Two vertices joined by an edge are adjacent; a vertex’s degree is its number of edges.
  • A path is a sequence of vertices, each adjacent to the next. A cycle is a path that returns to where it started.
  • A graph is connected if every vertex can be reached from every other.
  • Edges can carry weights, such as distances or costs.

Graphs model roads between cities, links between web pages, friendships, dependencies between tasks, and moves between states of a puzzle.

A zoo of problems

CS61B lists graph problems to show how differently they behave. With V vertices and E edges:

Problem Difficulty
Is there a path from s to t? easy: DFS or BFS, O(V + E)
Shortest path from s to t, by edges easy: BFS, O(V + E)
Shortest path with weights Dijkstra, Lesson 45
Is there a cycle? easy: DFS
Is there a tour using every edge exactly once (Euler tour)? easy: every vertex has even degree, Euler, 1736
Is there a tour visiting every vertex exactly once (Hamilton tour)? no efficient algorithm is known
Can the graph be drawn without crossing edges (planarity)? possible in linear time, but hard to write
Are two graphs the same up to renaming vertices (isomorphism)? an open research problem

The Euler and Hamilton problems sound almost identical, and one is easy while the other is among the hardest known. Lesson 58 returns to why.

Is there a path from s to t? Walk from s to a neighbor, then to one of its neighbors, and so on, going as deep as possible before backing up. To avoid walking in circles, mark every vertex when you first visit it, and never visit a marked vertex again.

// An undirected graph as a dictionary from each vertex to its neighbors.
let graph: [Int: [Int]] = [
    0: [1, 2], 1: [0, 4], 2: [0, 3, 4], 3: [2, 5], 4: [1, 2], 5: [3],
    6: [7], 7: [6],
]

func connected(_ s: Int, _ t: Int, in graph: [Int: [Int]]) -> Bool {
    var marked: Set<Int> = []
    func visit(_ v: Int) -> Bool {
        if v == t { return true }
        marked.insert(v)
        for w in graph[v, default: []] where !marked.contains(w) {
            if visit(w) { return true }
        }
        return false
    }
    return visit(s)
}

print(connected(0, 5, in: graph), connected(0, 7, in: graph))   // true false

Every vertex is marked at most once, and for each vertex its list of neighbors is examined once, so depth-first search takes O(V + E) time. It is optimal: any algorithm must at least look at the vertices and edges.

Finding the path

Knowing that a path exists is often not enough. When DFS first reaches w from v, record edgeTo[w] = v. Those records form a tree rooted at s, and following them back from t gives the path, in reverse:

let graph: [Int: [Int]] = [0: [1, 2], 1: [0, 4], 2: [0, 3, 4], 3: [2, 5], 4: [1, 2], 5: [3]]

func depthFirstPaths(from s: Int, in graph: [Int: [Int]]) -> [Int: Int] {
    var edgeTo: [Int: Int] = [:]
    var marked: Set = [s]
    func visit(_ v: Int) {
        for w in graph[v, default: []] where !marked.contains(w) {
            marked.insert(w)
            edgeTo[w] = v
            visit(w)
        }
    }
    visit(s)
    return edgeTo
}

func path(to t: Int, from s: Int, edgeTo: [Int: Int]) -> [Int]? {
    guard t == s || edgeTo[t] != nil else { return nil }
    var path = [t]
    while let previous = edgeTo[path.last!] {
        path.append(previous)
    }
    return path.reversed()
}

let edgeTo = depthFirstPaths(from: 0, in: graph)
print(path(to: 5, from: 0, edgeTo: edgeTo)!, path(to: 4, from: 0, edgeTo: edgeTo)!)
// [0, 1, 4, 2, 3, 5] [0, 1, 4]

The path DFS finds to 5 is correct, but long: it wandered through 1 and 4 before reaching 2, because it always goes deep first. There is a shorter path, 0–2–3–5.

What would Swift print?

let graph: [Int: [Int]] = [0: [1, 3], 1: [2], 2: [], 3: [2, 4], 4: []]
var order: [Int] = []
var marked: Set<Int> = []
func dfs(_ v: Int) {
    marked.insert(v)
    order.append(v)
    for w in graph[v]! where !marked.contains(w) {
        dfs(w)
    }
}
dfs(0)
print(order)

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

Show answer and explanation

Answer[0, 1, 2, 3, 4]

From 0, DFS goes to 1 and all the way to 2 before backing up. Back at 0, it tries 3; 3’s neighbor 2 is already marked, so it goes on to 4. This is a pre-order of the tree of first visits.

To find the path with the fewest edges, explore in order of distance: first all neighbors of s, then all their unvisited neighbors, and so on, like level order in a tree. A queue holds the vertices waiting to be explored, oldest first:

let graph: [Int: [Int]] = [0: [1, 2], 1: [0, 4], 2: [0, 3, 4], 3: [2, 5], 4: [1, 2], 5: [3]]

func breadthFirstPaths(from s: Int, in graph: [Int: [Int]]) -> (edgeTo: [Int: Int], distTo: [Int: Int]) {
    var edgeTo: [Int: Int] = [:]
    var distTo = [s: 0]
    var queue = [s]
    var head = 0
    while head < queue.count {
        let v = queue[head]
        head += 1
        for w in graph[v, default: []] where distTo[w] == nil {
            distTo[w] = distTo[v]! + 1
            edgeTo[w] = v
            queue.append(w)
        }
    }
    return (edgeTo, distTo)
}

let (edgeTo, distTo) = breadthFirstPaths(from: 0, in: graph)
var path = [5]
while let previous = edgeTo[path.last!] {
    path.append(previous)
}
print(Array(path.reversed()), distTo[5]!)   // [0, 2, 3, 5] 3

The queue is an array with a head index, rather than removeFirst(), which Lesson 37 showed is linear. Vertices are marked (here, given a distance) when they are added to the queue, not when they are taken out, so no vertex is queued twice. BFS is also O(V + E), and every path it finds has the fewest possible edges: it visits all vertices at distance k before any at distance k + 1.

Put the lines in order

Put the lines in order so the program prints [0, 1, 2, 3].

  1. head += 1
  2. for w in graph[v]! where seen.insert(w).inserted {
  3. let graph = [0: [1, 2], 1: [3], 2: [3], 3: []]
  4. }
  5. }
  6. while head < queue.count {
  7. var queue = [0], seen: Set = [0]
  8. var head = 0
  9. print(queue)
  10. let v = queue[head]
  11. queue.append(w)

Show the correct program
let graph = [0: [1, 2], 1: [3], 2: [3], 3: []]
var queue = [0], seen: Set = [0]
var head = 0
while head < queue.count {
    let v = queue[head]
    head += 1
    for w in graph[v]! where seen.insert(w).inserted {
        queue.append(w)
    }
}
print(queue)

Lab 42: Traversals

Q0: What would Swift print?

What would Swift print?

indirect enum Tree {
    case empty
    case node(Tree, Int, Tree)
}
func post(_ t: Tree) -> [Int] {
    guard case .node(let l, let v, let r) = t else { return [] }
    return post(l) + post(r) + [v]
}
let t = Tree.node(.node(.empty, 2, .node(.empty, 3, .empty)), 1, .node(.empty, 4, .empty))
print(post(t))

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

Show answer and explanation

Answer[3, 2, 4, 1]

Post-order finishes both subtrees before the node. 2’s only child is 3 on the right, so 3 comes before 2; the root, 1, comes last.

Q1: Levels

Write levels(_:), which returns a tree’s values grouped by depth, as an array of arrays, using level-order traversal.

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

func levels(_ t: Tree) -> [[Int]] {
    var result: [[Int]] = []
    var level = [t]
    while true {
        var values: [Int] = []
        var next: [Tree] = []
        for case .node(let l, let v, let r) in level {
            values.append(v)
            next += [l, r]
        }
        if values.isEmpty { return result }
        result.append(values)
        level = next
    }
}

let t = Tree.node(.node(.node(.empty, 4, .empty), 2, .empty), 1, .node(.node(.empty, 5, .empty), 3, .node(.empty, 6, .empty)))
assert(levels(t) == [[1], [2, 3], [4, 5, 6]])
assert(levels(.empty) == [])

Q2: Counting components

Write componentCount(_:vertices:), which counts the connected components of an undirected graph with vertices 0 to V − 1, by running DFS from every unmarked vertex. Use an explicit stack instead of recursion.

Show solution
func componentCount(_ graph: [Int: [Int]], vertices: Int) -> Int {
    var marked = Array(repeating: false, count: vertices)
    var count = 0
    for start in 0..<vertices where !marked[start] {
        count += 1
        var stack = [start]
        marked[start] = true
        while let v = stack.popLast() {
            for w in graph[v, default: []] where !marked[w] {
                marked[w] = true
                stack.append(w)
            }
        }
    }
    return count
}

let graph: [Int: [Int]] = [0: [1], 1: [0, 2], 2: [1], 3: [4], 4: [3]]
assert(componentCount(graph, vertices: 7) == 4)      // {0,1,2}, {3,4}, {5}, {6}
assert(componentCount([:], vertices: 3) == 3)

The explicit stack avoids running out of call stack on a large graph, like a long path of a million vertices, and makes the “container decides the order” idea from the lesson concrete. Lesson 35’s disjoint sets could answer the same question, one connect per edge.

Q3: Escape the maze

A maze is a grid of strings, # for walls and . for open cells, with S for the start and E for the exit. Find the length of the shortest path from S to E, moving up, down, left, or right, or nil if there is none. Treat each open cell as a vertex.

Show solution
func shortestEscape(_ maze: [String]) -> Int? {
    let grid = maze.map(Array.init)
    let rows = grid.count, columns = grid[0].count
    var start = (0, 0)
    for r in 0..<rows { for c in 0..<columns where grid[r][c] == "S" { start = (r, c) } }

    var distance = Array(repeating: Array(repeating: -1, count: columns), count: rows)
    distance[start.0][start.1] = 0
    var queue = [start]
    var head = 0
    while head < queue.count {
        let (r, c) = queue[head]
        head += 1
        if grid[r][c] == "E" { return distance[r][c] }
        for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
            let (nr, nc) = (r + dr, c + dc)
            if (0..<rows).contains(nr), (0..<columns).contains(nc),
               grid[nr][nc] != "#", distance[nr][nc] == -1 {
                distance[nr][nc] = distance[r][c] + 1
                queue.append((nr, nc))
            }
        }
    }
    return nil
}

assert(shortestEscape(["S.#",
                       ".##",
                       "..E"]) == 4)
assert(shortestEscape(["S#E"]) == nil)
assert(shortestEscape(["S.....E"]) == 6)

The graph is never built: each cell’s neighbors are computed when needed. That is common for grids, puzzles, and games, where the graph is implied by the rules.

Q4: Does it have a cycle?

Write hasCycle(_:vertices:) for an undirected graph. During DFS, reaching a marked vertex that is not the one you just came from means there is a cycle.

Show solution
func hasCycle(_ graph: [Int: [Int]], vertices: Int) -> Bool {
    var marked = Array(repeating: false, count: vertices)
    func visit(_ v: Int, from parent: Int?) -> Bool {
        marked[v] = true
        for w in graph[v, default: []] {
            if !marked[w] {
                if visit(w, from: v) { return true }
            } else if w != parent {
                return true
            }
        }
        return false
    }
    for v in 0..<vertices where !marked[v] {
        if visit(v, from: nil) { return true }
    }
    return false
}

let tree: [Int: [Int]] = [0: [1, 2], 1: [0], 2: [0, 3], 3: [2]]
let triangle: [Int: [Int]] = [0: [1, 2], 1: [0, 2], 2: [0, 1]]
assert(!hasCycle(tree, vertices: 4))
assert(hasCycle(triangle, vertices: 3))
assert(hasCycle([0: [1], 1: [0], 2: [3, 4], 3: [2, 4], 4: [2, 3]], vertices: 5))

In an undirected graph every edge appears in both vertices’ lists, so the edge back to the parent is always seen; it is not a cycle. (A graph with two parallel edges between the same vertices would need more care.)

Q5 (optional): Two colors

A graph is bipartite if its vertices can be colored with two colors so that every edge joins different colors: for example, people and the clubs they belong to. Write isBipartite(_:vertices:) with BFS, coloring each newly reached vertex opposite to the vertex it was reached from.

Show solution
func isBipartite(_ graph: [Int: [Int]], vertices: Int) -> Bool {
    var color = Array(repeating: -1, count: vertices)
    for start in 0..<vertices where color[start] == -1 {
        color[start] = 0
        var queue = [start]
        var head = 0
        while head < queue.count {
            let v = queue[head]
            head += 1
            for w in graph[v, default: []] {
                if color[w] == -1 {
                    color[w] = 1 - color[v]
                    queue.append(w)
                } else if color[w] == color[v] {
                    return false
                }
            }
        }
    }
    return true
}

let square: [Int: [Int]] = [0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [2, 0]]
let triangle: [Int: [Int]] = [0: [1, 2], 1: [0, 2], 2: [0, 1]]
assert(isBipartite(square, vertices: 4))
assert(!isBipartite(triangle, vertices: 3))

A graph is bipartite exactly when it has no cycle of odd length, and a triangle is the smallest odd cycle. BFS colors by the parity of the distance from the start, and an edge between two vertices of equal parity reveals an odd cycle.

What’s next

Dictionaries of arrays worked for small examples. Next lesson: how to store graphs properly, and what each representation costs.