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

LLRB set

Build a left-leaning red-black tree set: rotations, color flips, insertion, an invariant checker, ordered iteration, floor and ceiling, and a test that the height stays logarithmic.

This homework goes with Lesson 40. You will build a sorted set on a left-leaning red-black tree, the balanced search tree CS61B builds, and check that it stays balanced. Put everything in hw18.swift; each question adds to the same type.

Q1: Nodes, colors, and rotations

Write LLRBSet<Element: Comparable> as a structure with a private root of type Node?, where Node is a final class storing an element, a left and right child, and a Boolean isRed. Write the three helpers: rotateLeft(_:), rotateRight(_:), and flipColors(_:). Each returns the new root of the subtree it was given.

Show solution
struct LLRBSet<Element: Comparable> {
    final class Node {
        var element: Element
        var left: Node?
        var right: Node?
        var isRed: Bool
        init(_ element: Element, isRed: Bool = true) {
            self.element = element
            self.isRed = isRed
        }
    }

    private var root: Node?

    static func isRed(_ node: Node?) -> Bool { node?.isRed ?? false }

    static func rotateLeft(_ h: Node) -> Node {
        let x = h.right!
        h.right = x.left
        x.left = h
        x.isRed = h.isRed
        h.isRed = true
        return x
    }

    static func rotateRight(_ h: Node) -> Node {
        let x = h.left!
        h.left = x.right
        x.right = h
        x.isRed = h.isRed
        h.isRed = true
        return x
    }

    static func flipColors(_ h: Node) {
        h.isRed = true
        h.left!.isRed = false
        h.right!.isRed = false
    }
}

typealias Node = LLRBSet<Int>.Node
let h = Node(1, isRed: false)
h.right = Node(2)
let top = LLRBSet<Int>.rotateLeft(h)
assert(top.element == 2 && !top.isRed && top.left!.element == 1 && top.left!.isRed)

A rotation keeps the order of the elements and hands its old color to the new subtree root, so the black height stays the same above it.

Q2: Insertion

Add insert(_:), returning true if the element was new. Insert as in a plain search tree, with a new red node, then fix the tree on the way back up with the three rules from Lesson 40, and color the root black.

Show solution
struct LLRBSet<Element: Comparable> {
    final class Node {
        var element: Element
        var left: Node?
        var right: Node?
        var isRed = true
        init(_ element: Element) { self.element = element }
    }

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

    private static func isRed(_ node: Node?) -> Bool { node?.isRed ?? false }

    private static func rotateLeft(_ h: Node) -> Node {
        let x = h.right!
        h.right = x.left; x.left = h
        x.isRed = h.isRed; h.isRed = true
        return x
    }

    private static func rotateRight(_ h: Node) -> Node {
        let x = h.left!
        h.left = x.right; x.right = h
        x.isRed = h.isRed; h.isRed = true
        return x
    }

    private static func flipColors(_ h: Node) {
        h.isRed = true; h.left!.isRed = false; h.right!.isRed = false
    }

    @discardableResult
    mutating func insert(_ element: Element) -> Bool {
        var added = false
        root = Self.insert(element, into: root, added: &added)
        root!.isRed = false
        if added { count += 1 }
        return added
    }

    private static func insert(_ element: Element, into node: Node?, added: inout Bool) -> Node {
        guard var h = node else {
            added = true
            return Node(element)
        }
        if element < h.element {
            h.left = insert(element, into: h.left, added: &added)
        } else if element > h.element {
            h.right = insert(element, into: h.right, added: &added)
        }
        if isRed(h.right) && !isRed(h.left) { h = rotateLeft(h) }
        if isRed(h.left) && isRed(h.left?.left) { h = rotateRight(h) }
        if isRed(h.left) && isRed(h.right) { flipColors(h) }
        return h
    }

    func contains(_ element: Element) -> Bool {
        var node = root
        while let n = node {
            if element < n.element { node = n.left }
            else if element > n.element { node = n.right }
            else { return true }
        }
        return false
    }
}

var set = LLRBSet<Int>()
assert(set.insert(5) && set.insert(3) && !set.insert(5))
for n in [8, 1, 4, 7, 9] { set.insert(n) }
assert(set.count == 7 && set.contains(4) && !set.contains(6))

The three rules run in this order at every node on the path back up, and each one creates at most one of the situations the next one fixes. Because Node is a class, the structure shares its tree between copies; Q5 deals with that.

Q3: Checking the invariants

Write isValid, which checks the four properties of a left-leaning red-black tree: search-tree order, no red right links, no two red links in a row, and the same number of black links on every path from the root to a missing child. Then insert 10,000 random numbers, checking validity every 1,000 insertions, and check that the height is at most 2 log₂ N.

Show solution

Add these members to the LLRBSet of Q2:

var isValid: Bool {
    guard !Self.isRed(root) else { return false }
    return Self.check(root, low: nil, high: nil) != nil
}

/// The black height of the subtree, or nil if it breaks an invariant.
private static func check(_ node: Node?, low: Element?, high: Element?) -> Int? {
    guard let n = node else { return 0 }
    if let low, n.element <= low { return nil }
    if let high, n.element >= high { return nil }
    if isRed(n.right) { return nil }
    if n.isRed && isRed(n.left) { return nil }
    guard let left = check(n.left, low: low, high: n.element),
          let right = check(n.right, low: n.element, high: high),
          left == right else { return nil }
    return left + (n.isRed ? 0 : 1)
}

var height: Int { Self.height(root) }

private static func height(_ node: Node?) -> Int {
    guard let n = node else { return 0 }
    return 1 + Swift.max(height(n.left), height(n.right))
}
var set = LLRBSet<Int>()
for step in 1...10_000 {
    set.insert(Int.random(in: 0..<1_000_000))
    if step % 1_000 == 0 { assert(set.isValid) }
}
let log2N = Int.bitWidth - set.count.leadingZeroBitCount   // bits in N: ⌊log₂ N⌋ + 1
assert(set.height <= 2 * log2N)

The red-link rules also guarantee the height bound: the longest path alternates red and black links, and the black height is at most log₂ N, so the height is at most twice that. In practice the height stays well below the bound: for 10,000 random elements it is about 18 or 19, against log₂ N ≈ 13.3 for a perfect tree and a bound of about 26.6.

Q4: An ordered set

Add Sequence conformance that visits elements in increasing order, plus min, max, floor(_:) (the largest element ≤ x), and ceiling(_:) (the smallest element ≥ x).

Show solution

Add these members to the LLRBSet:

var min: Element? {
    var node = root
    while let left = node?.left { node = left }
    return node?.element
}

var max: Element? {
    var node = root
    while let right = node?.right { node = right }
    return node?.element
}

func floor(_ x: Element) -> Element? {
    var node = root
    var best: Element? = nil
    while let n = node {
        if n.element == x { return x }
        if n.element < x { best = n.element; node = n.right } else { node = n.left }
    }
    return best
}

func ceiling(_ x: Element) -> Element? {
    var node = root
    var best: Element? = nil
    while let n = node {
        if n.element == x { return x }
        if n.element > x { best = n.element; node = n.left } else { node = n.right }
    }
    return best
}
extension LLRBSet: Sequence {
    struct Iterator: IteratorProtocol {
        private var stack: [Node] = []
        init(root: Node?) { pushLeft(root) }

        private mutating func pushLeft(_ node: Node?) {
            var node = node
            while let n = node { stack.append(n); node = n.left }
        }

        mutating func next() -> Element? {
            guard let n = stack.popLast() else { return nil }
            pushLeft(n.right)
            return n.element
        }
    }

    func makeIterator() -> Iterator { Iterator(root: root) }
}

Then:

var set = LLRBSet<Int>()
for n in [50, 20, 80, 10, 30, 70, 90] { set.insert(n) }
assert(Array(set) == [10, 20, 30, 50, 70, 80, 90])
assert(set.floor(55) == 50 && set.ceiling(55) == 70 && set.floor(5) == nil)
assert(set.min == 10 && set.max == 90)

Inside the type, min and max now name these properties, so Q3’s height must write Swift.max to reach the global function.

The iterator keeps an explicit stack of the nodes whose left subtrees it has entered: an in-order traversal (Lesson 38) paused between elements. Each node is pushed and popped once, so a full iteration is Θ(N), and the stack never holds more than the height.

Q5: Value semantics

Because nodes are classes, var b = a; b.insert(1) would also change a. Fix this with copy-on-write (Lesson 33): before any mutation, if the root is shared, copy the tree. Test that copies are independent.

Show solution

Rotations and color flips change nodes in place, so the whole tree must be copied before a mutation when anyone else refers to it. Copying is Θ(N), but it happens only on the first mutation after a copy, not on every insertion:

private static func copy(_ node: Node?) -> Node? {
    guard let n = node else { return nil }
    let fresh = Node(n.element)
    fresh.isRed = n.isRed
    fresh.left = copy(n.left)
    fresh.right = copy(n.right)
    return fresh
}

@discardableResult
mutating func insert(_ element: Element) -> Bool {
    if !isKnownUniquelyReferenced(&root) { root = Self.copy(root) }
    var added = false
    root = Self.insert(element, into: root, added: &added)
    root!.isRed = false
    if added { count += 1 }
    return added
}
var a = LLRBSet<Int>()
for n in 1...5 { a.insert(n) }
var b = a
b.insert(6)
assert(Array(a) == [1, 2, 3, 4, 5] && Array(b) == [1, 2, 3, 4, 5, 6])

isKnownUniquelyReferenced(_:) only checks the root. That is enough here, because nodes are never shared between trees except through a shared root: every copy starts by copying the root, and with it the whole tree. (A persistent tree that shares unchanged subtrees between versions would need to copy along each path instead, as Swift’s own collections do with their buffers.)