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.
- Lessons
- Left-leaning red-black trees
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.)