BSTMap
Implement a complete ordered map as a binary search tree: put, get, contains, remove with Hibbard deletion, removeAll, count, keys in order through Sequence, and a randomized test against Dictionary.
This homework goes with Lesson 38, like CS61B’s BSTMap homework. You will build
a complete ordered map, one problem at a time, and test it against Swift’s own
Dictionary. Put everything in hw15.swift.
The map you build follows this protocol, CS61B’s Map61B in Swift:
protocol Map61B<Key, Value> {
associatedtype Key: Comparable
associatedtype Value
var count: Int { get }
mutating func put(_ key: Key, _ value: Value)
func get(_ key: Key) -> Value?
func containsKey(_ key: Key) -> Bool
mutating func remove(_ key: Key) -> Value?
mutating func removeAll()
}
Q1: Putting and getting
Write BSTMap<Key: Comparable, Value> as a class with a private nested node
class, and implement count, put, get, and containsKey. put on an
existing key replaces its value without changing count.
Show solution
final class BSTMap<Key: Comparable, Value> {
private final class Node {
let key: Key
var value: Value
var left: Node?
var right: Node?
init(_ key: Key, _ value: Value) {
self.key = key
self.value = value
}
}
private var root: Node?
private(set) var count = 0
func put(_ key: Key, _ value: Value) {
root = put(root, key, value)
}
private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
guard let node else {
count += 1
return Node(key, value)
}
if key < node.key { node.left = put(node.left, key, value) }
else if key > node.key { node.right = put(node.right, key, value) }
else { node.value = value }
return node
}
func get(_ key: Key) -> Value? {
var node = root
while let current = node {
if key < current.key { node = current.left }
else if key > current.key { node = current.right }
else { return current.value }
}
return nil
}
func containsKey(_ key: Key) -> Bool {
get(key) != nil
}
}
let map = BSTMap<String, Int>()
map.put("hi", 1)
map.put("hello", 2)
map.put("hi", 3)
assert(map.count == 2 && map.get("hi") == 3 && map.get("hey") == nil)
assert(map.containsKey("hello") && !map.containsKey("hey"))containsKey through get is correct here because values are not optional. For
a map whose values could themselves be nil, it would need its own search.
Q2: Keys in order
Make BSTMap a Sequence of (key: Key, value: Value) pairs, in increasing key
order, with an iterator that uses an explicit stack instead of recursion, so it
produces one pair at a time.
Show solution
final class BSTMap<Key: Comparable, Value> {
fileprivate final class Node {
let key: Key
var value: Value
var left: Node?
var right: Node?
init(_ key: Key, _ value: Value) {
self.key = key
self.value = value
}
}
fileprivate var root: Node?
private(set) var count = 0
func put(_ key: Key, _ value: Value) {
root = put(root, key, value)
}
private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
guard let node else { count += 1; return Node(key, value) }
if key < node.key { node.left = put(node.left, key, value) }
else if key > node.key { node.right = put(node.right, key, value) }
else { node.value = value }
return node
}
}
extension BSTMap: Sequence {
struct Iterator: IteratorProtocol {
private var stack: [Node] = []
fileprivate init(root: Node?) {
pushLeftPath(from: root)
}
private mutating func pushLeftPath(from node: Node?) {
var node = node
while let current = node {
stack.append(current)
node = current.left
}
}
mutating func next() -> (key: Key, value: Value)? {
guard let node = stack.popLast() else { return nil }
pushLeftPath(from: node.right)
return (node.key, node.value)
}
}
func makeIterator() -> Iterator {
Iterator(root: root)
}
}
let map = BSTMap<Int, String>()
for (k, v) in [(5, "e"), (2, "b"), (8, "h"), (1, "a"), (3, "c")] {
map.put(k, v)
}
assert(map.map(\.key) == [1, 2, 3, 5, 8])
assert(map.map(\.value).joined() == "abceh")
assert(map.first { $0.key > 4 }!.value == "e")The stack holds the path of nodes whose left subtrees are being visited. Each
next takes the top node, then pushes the leftmost path of its right subtree.
Every node is pushed and popped once, so a full traversal is Θ(N), and the stack
never holds more than the tree’s height.
Q3: Removing
Add remove(_:), which removes a key and returns its value, using Hibbard
deletion with the successor, and removeAll().
Show solution
final class BSTMap<Key: Comparable, Value> {
private final class Node {
let key: Key
var value: Value
var left: Node?
var right: Node?
init(_ key: Key, _ value: Value) {
self.key = key
self.value = value
}
}
private var root: Node?
private(set) var count = 0
func put(_ key: Key, _ value: Value) { root = put(root, key, value) }
private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
guard let node else { count += 1; return Node(key, value) }
if key < node.key { node.left = put(node.left, key, value) }
else if key > node.key { node.right = put(node.right, key, value) }
else { node.value = value }
return node
}
func get(_ key: Key) -> Value? {
var node = root
while let current = node {
if key < current.key { node = current.left }
else if key > current.key { node = current.right }
else { return current.value }
}
return nil
}
@discardableResult
func remove(_ key: Key) -> Value? {
guard let value = get(key) else { return nil }
root = remove(root, key)
count -= 1
return value
}
private func remove(_ node: Node?, _ key: Key) -> Node? {
guard let node else { return nil }
if key < node.key { node.left = remove(node.left, key); return node }
if key > node.key { node.right = remove(node.right, key); return node }
guard let left = node.left else { return node.right }
guard let right = node.right else { return left }
var successor = right
while let smaller = successor.left { successor = smaller }
successor.right = remove(right, successor.key)
successor.left = left
return successor
}
func removeAll() {
root = nil
count = 0
}
var keys: [Key] {
var result: [Key] = []
func visit(_ node: Node?) {
guard let node else { return }
visit(node.left); result.append(node.key); visit(node.right)
}
visit(root)
return result
}
}
let map = BSTMap<Int, Int>()
for k in [50, 30, 70, 20, 40, 60, 80] { map.put(k, k * 10) }
assert(map.remove(30) == 300 && map.remove(50) == 500 && map.remove(99) == nil)
assert(map.keys == [20, 40, 60, 70, 80] && map.count == 5)
map.removeAll()
assert(map.count == 0 && map.get(20) == nil)Looking the key up first makes the count easy to keep right: it only changes
when the key was there. removeAll simply drops the root; ARC frees every node,
since nothing else refers to them.
Q4: Testing against Dictionary
Write a randomized test that performs 20,000 random put, get, and remove
operations on a BSTMap and on a [Int: Int] dictionary, checking after each
that they agree, and at the end that the map’s keys are the dictionary’s keys,
sorted.
Show solution
final class BSTMap<Key: Comparable, Value> {
private final class Node {
let key: Key
var value: Value
var left: Node?
var right: Node?
init(_ key: Key, _ value: Value) { self.key = key; self.value = value }
}
private var root: Node?
private(set) var count = 0
func put(_ key: Key, _ value: Value) { root = put(root, key, value) }
private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
guard let node else { count += 1; return Node(key, value) }
if key < node.key { node.left = put(node.left, key, value) }
else if key > node.key { node.right = put(node.right, key, value) }
else { node.value = value }
return node
}
func get(_ key: Key) -> Value? {
var node = root
while let c = node { if key < c.key { node = c.left } else if key > c.key { node = c.right } else { return c.value } }
return nil
}
@discardableResult func remove(_ key: Key) -> Value? {
guard let value = get(key) else { return nil }
root = remove(root, key); count -= 1; return value
}
private func remove(_ node: Node?, _ key: Key) -> Node? {
guard let node else { return nil }
if key < node.key { node.left = remove(node.left, key); return node }
if key > node.key { node.right = remove(node.right, key); return node }
guard let left = node.left else { return node.right }
guard let right = node.right else { return left }
var s = right
while let smaller = s.left { s = smaller }
s.right = remove(right, s.key); s.left = left
return s
}
var keys: [Key] {
var result: [Key] = []
func visit(_ n: Node?) { guard let n else { return }; visit(n.left); result.append(n.key); visit(n.right) }
visit(root)
return result
}
}
let map = BSTMap<Int, Int>()
var reference: [Int: Int] = [:]
var generator = SystemRandomNumberGenerator()
for step in 0..<20_000 {
let key = Int.random(in: 0..<500, using: &generator)
switch Int.random(in: 0..<3, using: &generator) {
case 0:
map.put(key, step)
reference[key] = step
case 1:
assert(map.get(key) == reference[key])
default:
assert(map.remove(key) == reference.removeValue(forKey: key))
}
assert(map.count == reference.count)
}
assert(map.keys == reference.keys.sorted())Keys from a small range make collisions, replacements, and removals of present keys common, which is where bugs hide. The dictionary is the trusted reference; the map adds the one thing the dictionary lacks, sorted keys.
Q5 (optional): Order statistics
Store in each node the size of its subtree, keep it correct in put, and use it
to write select(_:), the key of rank k (the k-th smallest, from 0), and
rank(_:), the number of keys less than a given key, both in time proportional
to the height.
Show solution
final class RankedMap<Key: Comparable> {
private final class Node {
let key: Key
var left: Node?
var right: Node?
var size = 1
init(_ key: Key) { self.key = key }
}
private var root: Node?
private func size(_ node: Node?) -> Int { node?.size ?? 0 }
func insert(_ key: Key) { root = insert(root, key) }
private func insert(_ node: Node?, _ key: Key) -> Node {
guard let node else { return Node(key) }
if key < node.key { node.left = insert(node.left, key) }
else if key > node.key { node.right = insert(node.right, key) }
node.size = 1 + size(node.left) + size(node.right)
return node
}
func select(_ k: Int) -> Key? {
var node = root
var k = k
while let current = node {
let leftSize = size(current.left)
if k < leftSize { node = current.left }
else if k > leftSize { k -= leftSize + 1; node = current.right }
else { return current.key }
}
return nil
}
func rank(_ key: Key) -> Int {
var node = root
var rank = 0
while let current = node {
if key < current.key { node = current.left }
else if key > current.key { rank += size(current.left) + 1; node = current.right }
else { return rank + size(current.left) }
}
return rank
}
}
let map = RankedMap<Int>()
for k in [50, 30, 70, 20, 40, 60, 80] { map.insert(k) }
assert((0..<7).map { map.select($0)! } == [20, 30, 40, 50, 60, 70, 80])
assert(map.rank(50) == 3 && map.rank(45) == 3 && map.rank(10) == 0 && map.rank(99) == 7)
assert(map.select(7) == nil)A node’s left subtree holds exactly the keys smaller than it within its subtree,
so its size says whether rank k is to the left, at the node, or to the right.
Recomputing size on the way back up from put keeps every size correct with no
extra walk.