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

Left-leaning red-black trees

Rotations that reshape a tree without breaking its order, how a binary tree can represent a 2-3 tree with red links, the three rules of a left-leaning red-black tree, and insertion with rotations and color flips.

CS61B
Red-Black Trees · Textbook Ch. 17
Swift book
Enumerations

B-trees stay balanced, but their nodes come in different sizes, with arrays of keys and children to shuffle on every split. Can an ordinary binary search tree, with one key per node, have a 2-3 tree’s guarantee? It can, and the result, the left-leaning red-black tree (LLRB), invented by Robert Sedgewick, is one of the most elegant data structures in this course. CS61B builds it in two steps.

Rotations

A rotation changes the shape of a BST without changing its order. Rotating left at a node h whose right child is x makes x the root of that subtree, with h as its left child. The subtree x used to have on its left moves over to become h’s right subtree:

     h                    x
    / \                  / \
   A   x     rotate     h   C
      / \    left ─▶   / \
     B   C            A   B

Every key in A is less than h, every key in B is between h and x, and every key in C is greater than x, before and after. Rotating right is the mirror image. Each rotation changes three links and takes constant time.

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 rotateLeft(_ h: Node) -> Node {
    let x = h.right!
    h.right = x.left
    x.left = h
    return x
}

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

let before = Node(2, Node(1), Node(4, Node(3), Node(5)))
let after = rotateLeft(before)
print(after.key, after.left!.key, inorder(after))   // 4 2 [1, 2, 3, 4, 5]

Rotations can shorten a tree: rotating at the right place moves a long path up by one level. The question is which rotations to do, and when.

A 2-3 tree in disguise

A 2-3 tree has 2-nodes (one key, two children) and 3-nodes (two keys, three children). A 3-node can be drawn as two binary nodes joined by a special link, with the smaller key as the left child of the larger:

   2-3 tree:      [ b  d ]              as a binary tree:      d
                 /   |   \                                   //  \
               [a]  [c]  [e]                                b    e
                                                           / \
                                                          a   c

The doubled link // is the red link: it glues two binary nodes into one 2-3 node. Every other link is black. Store the color in the child node, as the color of the link that points to it.

A binary tree that corresponds this way to a 2-3 tree follows three rules:

  1. Red links lean left. A 3-node is always drawn with its smaller key below and to the left.
  2. No node has two red links touching it. That would be a 4-node, which a 2-3 tree does not allow.
  3. Every path from the root to an empty link has the same number of black links. This is the 2-3 tree’s “all leaves at the same depth”, since black links are exactly the links between 2-3 nodes.

A tree with these properties is a left-leaning red-black tree. Rule 3 bounds its height: the black links on any path number at most log₂ N, as in a 2-3 tree, and by rule 2 at most every other link can be red, so no path is longer than 2 log₂ N.

Insertion

Insert as in an ordinary BST, and color the new node’s link red: the new key joins an existing node, as it would in a 2-3 tree. That can break rule 1 or rule 2, and on the way back up the tree, three fixes restore them:

  • A right-leaning red link: rotate left.
  • Two red links in a row on the left: rotate right. This makes a node with two red children, a temporary 4-node.
  • Both children red: flip colors. Make both children black and the node itself red. In the 2-3 tree, this is the split: the middle key moves up into its parent.

Applied in that order, at every node on the path back to the root, they restore all three rules. Finally, the root’s color is set to black, since there is no link above it.

final class LLRB<Key: Comparable> {
    private final class Node {
        let key: Key
        var left: Node?
        var right: Node?
        var isRed = true               // the color of the link from the parent

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

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

    private func isRed(_ node: Node?) -> Bool {
        node?.isRed ?? false           // empty links are black
    }

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

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

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

    func insert(_ key: Key) {
        root = insert(root, key)
        root!.isRed = false
    }

    private func insert(_ node: Node?, _ key: Key) -> Node {
        guard var h = node else {
            count += 1
            return Node(key)                          // a red link to the new node
        }
        if key < h.key {
            h.left = insert(h.left, key)
        } else if key > h.key {
            h.right = insert(h.right, key)
        }
        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(_ key: Key) -> Bool {
        var node = root
        while let current = node {
            if key < current.key { node = current.left }
            else if key > current.key { node = current.right }
            else { return true }
        }
        return false
    }

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

let tree = LLRB<Int>()
for key in 1...100_000 {             // sorted: a plain BST would be 100,000 deep
    tree.insert(key)
}
print(tree.count, tree.height, tree.contains(77_777), tree.rotations < 3 * tree.count)   // 100000 16 true true

Inserting 100,000 sorted keys gives a tree of height 16, where log₂ N is about 16.6. The rotations, which are the only extra work, average fewer than three per insertion.

The rotations recolor too: the new subtree root takes the old root’s color, and the old root becomes red, since it is now joined to the new root in the same 2-3 node.

What would Swift print?

final class Node {
    let key: Int
    var left: Node?
    var right: Node?
    var isRed = true
    init(_ key: Int) { self.key = key }
}
func isRed(_ n: Node?) -> Bool { n?.isRed ?? false }
var rotations = 0
func rotateLeft(_ h: Node) -> Node {
    let x = h.right!
    h.right = x.left; x.left = h
    x.isRed = h.isRed; h.isRed = true
    rotations += 1
    return x
}
func rotateRight(_ h: Node) -> Node {
    let x = h.left!
    h.left = x.right; x.right = h
    x.isRed = h.isRed; h.isRed = true
    rotations += 1
    return x
}
func insert(_ node: Node?, _ key: Int) -> Node {
    guard var h = node else { return Node(key) }
    if key < h.key { h.left = insert(h.left, key) } else if key > h.key { h.right = insert(h.right, key) }
    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) { h.isRed = true; h.left!.isRed = false; h.right!.isRed = false }
    return h
}
var root: Node? = nil
for k in [1, 2, 3] {
    root = insert(root, k)
    root!.isRed = false
}
print(root!.key, root!.left!.key, root!.right!.key, rotations)

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

Show answer and explanation

Answer2 1 3 1

Inserting 2 after 1 makes a right-leaning red link: one left rotation makes 2 the root with 1 as its red left child, the 3-node [1 2]. Inserting 3 gives 2 two red children at once, and a color flip splits them, with no rotation. The result is perfectly balanced: in the 2-3 tree, [1 2 3] split into [2] over [1] and [3].

Where red-black trees are used

Red-black trees, in the classic form rather than the left-leaning one, are the ordered maps in Java (TreeMap), C++ (std::map), and the Linux kernel’s scheduler. Swift’s standard library has no ordered map, and the Swift Collections package provides ordered collections of a different design, so a Swift program that needs one uses a package or builds one, as Homework 18 does.

Put the lines in order

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

  1. let (newRoot, newRight) = (left, root)
  2. var keys = [4, 3, 2]
  3. let left = keys.removeFirst()
  4. print(newRoot, [keys[0], newRoot, newRight])
  5. let root = keys.removeFirst()

Show the correct program
var keys = [4, 3, 2]
let root = keys.removeFirst()
let left = keys.removeFirst()
let (newRoot, newRight) = (left, root)
print(newRoot, [keys[0], newRoot, newRight])

Lab 39: Red-black trees

Q0: What would Swift print?

What would Swift print?

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 rotateRight(_ h: Node) -> Node {
    let x = h.left!
    h.left = x.right
    x.right = h
    return x
}
let t = rotateRight(Node(5, Node(3, Node(2), Node(4)), Node(8)))
print(t.key, t.right!.key, t.right!.left!.key, t.right!.right!.key)

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

Show answer and explanation

Answer3 5 4 8

Rotating right at 5 makes 3 the root. 5 becomes its right child, and 3’s old right subtree, 4, becomes 5’s left: it is still between 3 and 5.

Q1: Check the rules

Add a method checkRules() to LLRB that verifies that the tree is a BST, that no red link leans right, that no node has two red links touching it, and that every path from the root to an empty link has the same number of black links. Then check it after every one of 5,000 random insertions.

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

    private(set) var root: Node?

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

    private 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 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
    }

    func insert(_ key: Int) {
        root = insert(root, key)
        root!.isRed = false
    }

    private func insert(_ node: Node?, _ key: Int) -> Node {
        guard var h = node else { return Node(key) }
        if key < h.key { h.left = insert(h.left, key) }
        else if key > h.key { h.right = insert(h.right, key) }
        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) {
            h.isRed = true; h.left!.isRed = false; h.right!.isRed = false
        }
        return h
    }

    func checkRules() -> Bool {
        var blackHeight: Int? = nil
        func check(_ node: Node?, low: Int?, high: Int?, blacks: Int) -> Bool {
            guard let node else {
                if blackHeight == nil { blackHeight = blacks }
                return blackHeight == blacks
            }
            if let low, node.key <= low { return false }
            if let high, node.key >= high { return false }
            if isRed(node.right) { return false }                       // leans right
            if node.isRed && isRed(node.left) { return false }          // two reds in a row
            let blacksBelow = blacks + (node.isRed ? 0 : 1)
            return check(node.left, low: low, high: node.key, blacks: blacksBelow)
                && check(node.right, low: node.key, high: high, blacks: blacksBelow)
        }
        return !isRed(root) && check(root, low: nil, high: nil, blacks: 0)
    }
}

let tree = LLRB()
var generator = SystemRandomNumberGenerator()
for _ in 0..<5_000 {
    tree.insert(Int.random(in: 0..<100_000, using: &generator))
    assert(tree.checkRules())
}

With red links always on the left, a node with two red links touching it can only be a red node with a red left child, so that is the case to check. The black count is taken at every empty link, where each path ends.

Q2: The height bound, measured

Insert 2¹⁶ − 1 keys into an LLRB tree in three orders, sorted, reversed, and random, and check that each height is at most 2 log₂ N. What do you notice about the sorted case?

Show solution
final class LLRB {
    private final class Node {
        let key: Int
        var left: Node?
        var right: Node?
        var isRed = true
        init(_ key: Int) { self.key = key }
    }
    private var root: Node?
    private func isRed(_ n: Node?) -> Bool { n?.isRed ?? false }
    private 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 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
    }
    func insert(_ key: Int) { root = insert(root, key); root!.isRed = false }
    private func insert(_ node: Node?, _ key: Int) -> Node {
        guard var h = node else { return Node(key) }
        if key < h.key { h.left = insert(h.left, key) } else if key > h.key { h.right = insert(h.right, key) }
        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) { h.isRed = true; h.left!.isRed = false; h.right!.isRed = false }
        return h
    }
    var height: Int {
        func height(_ n: Node?) -> Int { n.map { 1 + max(height($0.left), height($0.right)) } ?? -1 }
        return height(root)
    }
}

let n = (1 << 16) - 1
func heightAfter(_ keys: [Int]) -> Int {
    let tree = LLRB()
    for key in keys { tree.insert(key) }
    return tree.height
}

let sorted = heightAfter(Array(1...n))
let reversed = heightAfter(Array((1...n).reversed()))
let random = heightAfter(Array(1...n).shuffled())
assert([sorted, reversed, random].allSatisfy { $0 <= 32 })
assert(sorted == 15)

Sorted input, the worst case for a plain BST, gives a perfectly balanced tree: height 15 for 2¹⁶ − 1 keys, the minimum possible. In the 2-3 tree, sorted insertions keep splitting the rightmost nodes, which builds a tree of 2-nodes only, and a 2-3 tree of 2-nodes has no red links at all.

Q3: 2-3 nodes

Each red link joins two binary nodes into one 3-node. Write threeNodes, which counts red links, and use it to compute the number of nodes the corresponding 2-3 tree has, for a tree built from 1,000 random keys. Check that the 2-3 tree’s nodes hold all the keys: 2-nodes hold one and 3-nodes hold two.

Show solution
final class LLRB {
    private final class Node {
        let key: Int
        var left: Node?
        var right: Node?
        var isRed = true
        init(_ key: Int) { self.key = key }
    }
    private var root: Node?
    private(set) var count = 0
    private func isRed(_ n: Node?) -> Bool { n?.isRed ?? false }
    private 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 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
    }
    func insert(_ key: Int) { root = insert(root, key); root!.isRed = false }
    private func insert(_ node: Node?, _ key: Int) -> Node {
        guard var h = node else { count += 1; return Node(key) }
        if key < h.key { h.left = insert(h.left, key) } else if key > h.key { h.right = insert(h.right, key) }
        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) { h.isRed = true; h.left!.isRed = false; h.right!.isRed = false }
        return h
    }
    var threeNodes: Int {
        func reds(_ n: Node?) -> Int {
            guard let n else { return 0 }
            return (n.isRed ? 1 : 0) + reds(n.left) + reds(n.right)
        }
        return reds(root)
    }
}

let tree = LLRB()
for key in Array(0..<1_000).shuffled() { tree.insert(key) }
let three = tree.threeNodes
let two = tree.count - 2 * three          // binary nodes not glued by a red link
assert(two + 2 * three == 1_000)
assert(two + three == tree.count - three)

Every red link removes one node from the count, since it merges two binary nodes into one 3-node. So the 2-3 tree has N − R nodes for N keys and R red links, and exactly R of them are 3-nodes.

Q4 (optional): Counting the work

Count rotations and color flips for 100,000 random insertions and for 100,000 sorted ones. Which order does more work? Predict first, then measure.

Show solution
final class LLRB {
    private final class Node {
        let key: Int
        var left: Node?
        var right: Node?
        var isRed = true
        init(_ key: Int) { self.key = key }
    }
    private var root: Node?
    private(set) var rotations = 0
    private(set) var flips = 0
    private func isRed(_ n: Node?) -> Bool { n?.isRed ?? false }
    private func rotateLeft(_ h: Node) -> Node {
        rotations += 1
        let x = h.right!; h.right = x.left; x.left = h
        x.isRed = h.isRed; h.isRed = true; return x
    }
    private func rotateRight(_ h: Node) -> Node {
        rotations += 1
        let x = h.left!; h.left = x.right; x.right = h
        x.isRed = h.isRed; h.isRed = true; return x
    }
    func insert(_ key: Int) { root = insert(root, key); root!.isRed = false }
    private func insert(_ node: Node?, _ key: Int) -> Node {
        guard var h = node else { return Node(key) }
        if key < h.key { h.left = insert(h.left, key) } else if key > h.key { h.right = insert(h.right, key) }
        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) {
            flips += 1
            h.isRed = true; h.left!.isRed = false; h.right!.isRed = false
        }
        return h
    }
}

let n = 100_000
let random = LLRB()
for key in Array(0..<n).shuffled() { random.insert(key) }
let sorted = LLRB()
for key in 0..<n { sorted.insert(key) }
assert(sorted.rotations <= n && sorted.rotations > n - 20)      // one per insertion, almost exactly
assert(random.rotations + random.flips < 3 * n && sorted.rotations + sorted.flips < 3 * n)

The two orders do about the same amount of work, a little under two fix-ups per insertion, but of different kinds. Sorted insertion always adds at the far right, making a right-leaning red link every time: almost exactly one left rotation per insertion, and about one color flip, as the 2-3 tree splits its rightmost nodes. Random insertion needed about 1.2 rotations and 0.75 flips per insertion in one run of this test. Either way, the extra work is a small constant per insertion on top of the Θ(log N) search, which is the point: balance costs almost nothing.

What’s next

Search trees keep everything in order. Sometimes only the smallest item matters. Next lesson: heaps and priority queues.