Sets, maps, and binary search trees
The set and map abstract data types, why sorted lists cannot be searched quickly, binary search trees with search, insertion, and Hibbard deletion, ordered operations, and how insertion order decides a tree’s height.
- CS61B
- Sets, Extends, and BSTs · Textbook Ch. 15
- Swift book
- Generics · Enumerations
- Documentation
- Set · Dictionary
Most programs need to look things up. A spelling checker asks whether a word is in its dictionary; a web server looks up a session by its token; a compiler looks up a name to find its type. The next five lessons are about the data structures that answer these questions quickly, starting with the binary search tree, which CS61B introduces by asking how to make a sorted list searchable.
Sets and maps
Two abstract data types cover almost every lookup:
- A set holds distinct items:
insert,contains, andremove. - A map (a dictionary, in Swift) associates each key with a value:
put(key, value),get(key),containsKey, andremove. A set is a map whose values do not matter.
Swift’s Set and Dictionary are hash tables, which Lessons 48 and 49
build. They are fast but keep no order. An ordered map, one that can list
its keys in sorted order and answer questions like “the largest key below 50”,
needs a different structure, and that is where trees come in.
Searching a sorted list
An ArraySet from Lesson 32 takes linear time for contains. A sorted array
can use binary search, taking Θ(log N), but inserting into it shifts items,
which takes Θ(N). A sorted linked list inserts cheaply once the position is
found, but finding it means walking from the front: binary search needs to jump
to the middle, and a linked list cannot.
CS61B’s idea is to add shortcuts. Keep a reference to the middle node, and let each half keep a reference to its own middle, and so on. The result is a tree in which each node splits the keys into those smaller than it, on the left, and those larger, on the right.
Binary search trees
A binary search tree (BST) is a binary tree in which, for every node, every key in its left subtree is smaller than the node’s key, and every key in its right subtree is larger. There are no duplicate keys.
dog
/ \
bag flat
/ \ / \
alf cat elf glut
To search, start at the root and go left or right by comparing: each comparison discards a whole subtree. To insert, search for the key; if it is not there, the search ends at an empty spot, and the new node goes there.
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 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 put(_ key: Key, _ value: Value) {
root = put(root, key, value)
}
/// Inserts into the subtree rooted at `node`, and returns its new root.
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
}
/// The keys in sorted order: an in-order traversal.
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 ages = BSTMap<String, Int>()
for (name, age) in [("dog", 3), ("bag", 1), ("flat", 5), ("alf", 9), ("cat", 2)] {
ages.put(name, age)
}
ages.put("dog", 4)
print(ages.get("cat")!, ages.get("dog")!, ages.get("zebra") as Any, ages.count, ages.keys)
// 2 4 nil 5 ["alf", "bag", "cat", "dog", "flat"]
The recursive put returns the new root of each subtree and reassigns it:
node.left = put(node.left, …). Most calls return the node they were given,
unchanged, but at the bottom the call receives nil and returns the new
node, and the parent’s assignment links it in. CS61B warns against the
alternative, arm’s-length recursion, which checks whether a child exists
before recursing into it. Letting the call itself handle the empty case avoids
a special case for the empty tree, just as Lesson 28’s sentinel did.
Listing the keys in order, left subtree, node, right subtree, visits them sorted. That ordered traversal is what a hash table cannot offer.
What would Swift print?
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> 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) }
return node
}
func height(_ node: Node?) -> Int {
guard let node else { return -1 }
return 1 + max(height(node.left), height(node.right))
}
var a: Node? = nil
for k in [4, 2, 6, 1, 3, 5, 7] { a = insert(a, k) }
var b: Node? = nil
for k in [1, 2, 3, 4, 5, 6, 7] { b = insert(b, k) }
print(height(a), height(b))Show answer and explanation
Answer2 6
The same seven keys make a perfectly balanced tree when the middle one comes first, and a path of height 6 when they arrive in sorted order: every key goes to the right of the one before.
Deleting
Removing a key has three cases, depending on the node’s children:
- No children: remove the node; its parent’s reference becomes
nil. - One child: the child takes the node’s place.
- Two children: the node must be replaced by a key that keeps the order intact: either the largest key in its left subtree (its predecessor) or the smallest in its right subtree (its successor). Take the successor, delete it from the right subtree (it has at most one child, since it has no left child), and put it where the removed node was.
This is Hibbard deletion. In the same recursive style as put:
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
}
count -= 1
guard let left = node.left else { return node.right } // cases 1 and 2
guard let right = node.right else { return left }
var successor = right // case 3
while let smaller = successor.left {
successor = smaller
}
count += 1 // the removal below is not a real removal
successor.right = remove(right, successor.key)
successor.left = left
return successor
}
The successor’s key and value move to the removed node’s position by moving the successor node itself: it is first removed from the right subtree, then given the removed node’s children.
Height is everything
Every operation walks one path from the root, so each takes time proportional to the tree’s height, the length of its longest path. That height depends entirely on the order in which keys were inserted:
- A bushy tree, like one built with the median first, has height about log₂ N. A million keys: about 20 levels.
- A spindly tree, like one built from sorted keys, is a linked list: height N − 1.
So a BST is Θ(log N) in the best case and Θ(N) in the worst. For keys inserted in random order, the average depth of a node is about 2 ln N, around 1.39 log₂ N, so random trees are bushy. But real data is often sorted or nearly sorted: timestamps, sequential ids, words from a dictionary file. A plain BST degrades exactly on the inputs most likely to occur. The next two lessons fix that with trees that stay balanced whatever the order.
Put the lines in order
Put the lines in order so the program prints 1.
}let middle = (low + high) / 2let sorted = [1, 3, 5, 7, 9]while low < high {print(low)var low = 0, high = sorted.count - 1if sorted[middle] < 3 { low = middle + 1 } else { high = middle }
Show the correct program
let sorted = [1, 3, 5, 7, 9]
var low = 0, high = sorted.count - 1
while low < high {
let middle = (low + high) / 2
if sorted[middle] < 3 { low = middle + 1 } else { high = middle }
}
print(low)Lab 37: Binary search trees
Each problem uses a node class like this one:
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
Q0: What would Swift print?
What would Swift print?
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> 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) }
return node
}
func preorder(_ node: Node?) -> [Int] {
guard let node else { return [] }
return [node.key] + preorder(node.left) + preorder(node.right)
}
var root: Node? = nil
for k in [5, 3, 8, 4, 1, 9] { root = insert(root, k) }
print(preorder(root))Show answer and explanation
Answer[5, 3, 1, 4, 8, 9]
A pre-order traversal lists a node before its subtrees. 5 is the root; 3 and 8 are its children; 1 and 4 go under 3; 9 goes right of 8. Inserting keys in this order rebuilds the same tree, which is how BSTs are often saved.
Q1: Floor and ceiling
Write floor(_:_:), the largest key ≤ x, and ceiling(_:_:), the smallest key
≥ x, each walking a single path from the root.
Show solution
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> 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) }
return node
}
func floor(_ root: Node?, _ x: Int) -> Int? {
var node = root
var best: Int? = nil
while let current = node {
if current.key == x { return x }
if current.key < x {
best = current.key // a candidate; look for a larger one
node = current.right
} else {
node = current.left
}
}
return best
}
func ceiling(_ root: Node?, _ x: Int) -> Int? {
var node = root
var best: Int? = nil
while let current = node {
if current.key == x { return x }
if current.key > x {
best = current.key
node = current.left
} else {
node = current.right
}
}
return best
}
var root: Node? = nil
for k in [50, 30, 70, 20, 40, 60, 80] { root = insert(root, k) }
assert(floor(root, 45) == 40 && floor(root, 50) == 50 && floor(root, 10) == nil)
assert(ceiling(root, 45) == 50 && ceiling(root, 65) == 70 && ceiling(root, 90) == nil)A node smaller than x is a possible floor, but a better one may lie to its right, so the search remembers it and continues right. The walk is one path, so the cost is the tree’s height.
Q2: Is it a BST?
Write isBST(_:). The obvious check, that each node is larger than its left
child and smaller than its right child, is wrong: find a tree it accepts that is
not a BST, then write a correct version.
Show solution
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 naive(_ node: Node?) -> Bool {
guard let node else { return true }
if let left = node.left, left.key >= node.key { return false }
if let right = node.right, right.key <= node.key { return false }
return naive(node.left) && naive(node.right)
}
func isBST(_ node: Node?, above low: Int? = nil, below high: Int? = nil) -> Bool {
guard let node else { return true }
if let low, node.key <= low { return false }
if let high, node.key >= high { return false }
return isBST(node.left, above: low, below: node.key)
&& isBST(node.right, above: node.key, below: high)
}
// 10
// /
// 5
// \
// 15 15 is right of 5, but in 10's left subtree
let tricky = Node(10, Node(5, nil, Node(15)))
assert(naive(tricky) && !isBST(tricky))
assert(isBST(Node(10, Node(5, Node(1), Node(7)), Node(20))))Every key in a left subtree must be smaller than every ancestor it hangs to the left of, not just its parent. Passing down the allowed range, narrowed at each step, checks exactly that, in one pass.
Q3: Random versus sorted
Build BSTs of 10,000 keys inserted in sorted order and in random order, and
compare their heights with log₂ 10,000 ≈ 13.3. Write insert and height
iteratively, since the sorted tree is 10,000 levels deep.
Show solution
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func build(_ keys: [Int]) -> Node? {
var root: Node? = nil
for key in keys {
guard let start = root else { root = Node(key); continue }
var node = start
while true {
if key < node.key {
if let left = node.left { node = left } else { node.left = Node(key); break }
} else {
if let right = node.right { node = right } else { node.right = Node(key); break }
}
}
}
return root
}
func height(_ root: Node?) -> Int {
guard let root else { return -1 }
var level = [root]
var height = -1
while !level.isEmpty {
height += 1
level = level.flatMap { [$0.left, $0.right].compactMap { $0 } }
}
return height
}
let n = 10_000
let spindly = build(Array(0..<n))
let bushy = build(Array(0..<n).shuffled())
assert(height(spindly) == n - 1)
assert(height(bushy) < 45) // typically about 30height goes level by level, a breadth-first traversal (Lesson 43), which
needs no recursion. The random tree is typically about 30 levels deep, a small
multiple of log₂ N, while the sorted one is a 10,000-node path.
Q4: Keys in a range
Write keys(in:) for a BST, returning the keys in a closed range in sorted
order, visiting only the subtrees that can contain keys in the range.
Show solution
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func insert(_ node: Node?, _ key: Int) -> 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) }
return node
}
var visited = 0
func keys(in range: ClosedRange<Int>, _ node: Node?) -> [Int] {
guard let node else { return [] }
visited += 1
var result: [Int] = []
if range.lowerBound < node.key {
result += keys(in: range, node.left)
}
if range.contains(node.key) {
result.append(node.key)
}
if range.upperBound > node.key {
result += keys(in: range, node.right)
}
return result
}
var root: Node? = nil
for k in [50, 30, 70, 20, 40, 60, 80, 10, 25, 65] { root = insert(root, k) }
assert(keys(in: 22...62, root) == [25, 30, 40, 50, 60])
visited = 0
_ = keys(in: 75...100, root)
assert(visited == 3) // 50, 70, 80: the left side is never enteredThe left subtree can only hold keys in range if the range starts below the node’s key, and similarly on the right. The cost is the height plus the number of keys reported, rather than the size of the tree.
Q5 (optional): A balanced tree from sorted keys
Given sorted, distinct keys, build the BST of minimum height: the median at the root, and each half built the same way. Check that 1,023 keys make a tree of height 9.
Show solution
final class Node {
let key: Int
var left: Node?
var right: Node?
init(_ key: Int) { self.key = key }
}
func balanced(_ keys: ArraySlice<Int>) -> Node? {
guard !keys.isEmpty else { return nil }
let middle = keys.startIndex + keys.count / 2
let node = Node(keys[middle])
node.left = balanced(keys[..<middle])
node.right = balanced(keys[(middle + 1)...])
return node
}
func height(_ node: Node?) -> Int {
guard let node else { return -1 }
return 1 + max(height(node.left), height(node.right))
}
func inorder(_ node: Node?) -> [Int] {
guard let node else { return [] }
return inorder(node.left) + [node.key] + inorder(node.right)
}
let keys = Array(1...1023)
let root = balanced(keys[...])
assert(height(root) == 9 && inorder(root) == keys)2¹⁰ − 1 = 1,023 keys fill a perfect tree of ten levels, height 9. This only works when all the keys are known in advance; a tree that must stay balanced while keys arrive one by one needs the ideas in the next two lessons.
What’s next
Next lesson: B-trees, which stay perfectly balanced by growing at the root rather than at the leaves.