Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 34 - Trees: recursive types, from lists to game trees

A chain of boxes each pointing to the next, ending in a null marker

Announcements




Learning objectives

By the end of today, you should be able to:

  • Explain why struct Node { next: Node } can't compile, and how Option<Box<Node>> fixes it
  • Draw the memory of a linked list and a tree: one block per node
  • Trace search and insert on a binary search tree, and say what each costs
  • Choose between Monday's Vec-backed heap and a pointer-based tree, and defend the choice

Not a block

Recall the table we've been building:

NeedUseUnder the hood
Pop the newestVecOne block
Pop the oldestVecDequeOne block, a head, % cap
Pop the biggestBinaryHeapOne block, (i - 1) / 2
Is this here?HashSetOne block of buckets, hash % buckets

In the pre-work we asked how you'd store a family tree, where each person can have any number of children. What ideas did you have?

The max-heap trick doesn't work here

Monday's heap fit in a Vec because the tree was a complete binary tree: rows laid end to end, so a parent is at (i - 1) / 2.

But if our tree had gaps:

       8              [8, 3, 10, 1, _, _, 14, _, _, _, _, _, _, 13, _]
      / \
     3   10            index:  0  1   2  3  4  5   6  7  8  9 10 11 12  13 14
    /      \
   1        14
           /
          13

The arithmetic still works. But that's six values in fifteen slots, and every row we add doubles the block. A chain of twenty nodes would need a million slots.

Instead, each node is going to have to say where its children are.

A pointer

That's a pointer! And we have one that owns what it points at: Box.

A node that points to a node

Start with one child, which makes a list. Each node holds a value and the rest of the list:

struct Node {
    value: i32,
    next: Node,     // the rest of the list
}

fn main() {}

Box breaks the loop

A Box is always one pointer, 8 bytes, whatever is on the other end. And the list has to end somewhere, so the pointer is optional:

struct Node {
    value: i32,
    next: Option<Box<Node>>,   // Some(pointer to the next node), or None at the end
}

Now a Node is an i32 plus one Option<Box>: 16 bytes, fixed.

The rest of the list lives on the heap, behind the pointer.

We call this structure, a list where each item points to the next, a linked list.

Where it lives: a list of three

let third = Node { value: 30, next: None };
let second = Node { value: 20, next: Some(Box::new(third)) };
let first = Node { value: 10, next: Some(Box::new(second)) };
let list: Option<Box<Node>> = Some(Box::new(first));
Stack:                            Heap:
┌─────────────────────────────┐   ┌──────────────────┐   ┌──────────────────┐   ┌──────────────────┐
│ main()                      │   │ value: 10        │   │ value: 20        │   │ value: 30        │
│ └ list: Option<Box<Node>>   │   │ next: Some(Box)  │   │ next: Some(Box)  │   │ next: None       │
│    = Some(ptr) ─────────────┼──▶│   └ ptr ─────────┼──▶│   └ ptr ─────────┼──▶│                  │
└─────────────────────────────┘   └──────────────────┘   └──────────────────┘   └──────────────────┘

Every Box::new is its own allocation, and the blocks can be anywhere on the heap.

The stack just holds one pointer.

Monday's BinaryHeap of a thousand numbers was one block. A list of a thousand is a thousand blocks.

The length of a list, by recursion

struct Node {
    value: i32,
    next: Option<Box<Node>>,
}

fn len(list: &Option<Box<Node>>) -> usize {
    match list {
        None => 0,                            // the end: nothing here
        Some(node) => 1 + len(&node.next),    // this one, plus the rest
    }
}

fn main() {
    let third = Node { value: 30, next: None };
    let second = Node { value: 20, next: Some(Box::new(third)) };
    let first = Node { value: 10, next: Some(Box::new(second)) };
    let list: Option<Box<Node>> = Some(Box::new(first));

    println!("len {}", len(&list));  
}

The type has two cases, so the function has two arms. A recursive type gets a recursive function, and the base case is None. We drew call trees like this for merge sort in the sorting lecture.

Activity 34, Problem 1: draw a list

See Problem 1 on Activity 34.

Answer.

Stack:                            Heap:
┌─────────────────────────────┐   ┌──────────────────┐   ┌──────────────────┐
│ main()                      │   │ value: 5         │   │ value: 9         │
│ └ list: Option<Box<Node>>   │   │ next: Some(Box)  │   │ next: None       │
│    = Some(ptr) ─────────────┼──▶│   └ ptr ─────────┼──▶│                  │
└─────────────────────────────┘   └──────────────────┘   └──────────────────┘
  1. Two blocks. A thousand nodes is a thousand blocks
  2. 2. len is called three times: on the 5, on the 9, and on the None at the end

Two children: a tree

Let's give each node a second next/child node:

struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

One next made a list. Two makes a binary tree.

         8
        / \
       3   10          Every node is a Node with a value and two
      / \    \         Option<Box<Node>>s. A missing child is None.
     1   6    14
        / \   /
       4   7 13

A binary search tree

Let's add one more property we might want.

The BST property, for every node:

  • Everything in the left subtree is smaller than the node
  • Everything in the right subtree is bigger than the node
         8          Left of 8: 3, 1, 6, 4, 7. All smaller.
        / \         Right of 8: 10, 14, 13. All bigger.
       3   10
      / \    \      Left of 3: 1. Right of 3: 6, 4, 7.
     1   6    14
        / \   /     ...and so on, at every node.
       4   7 13

It's the sorted order, hung from the middle. Read it left, node, right and you get 1, 3, 4, 6, 7, 8, 10, 13, 14.

Search: is 6 in there?

         8
        / \
       3   10
      / \    \
     1   6    14
        / \   /
       4   7 13

You want to know whether 6 is in the tree. Where do you start, and what tells you where to go next?

Search: one comparison per row

         8          6 < 8: go left
        / \
       3   10       6 > 3: go right
      / \    \
     1   6    14    6 == 6: found it
        / \   /
       4   7 13

Each comparison throws away a whole subtree. The cost is one step per row, so O(height).

For a tree that's roughly balanced, height is about . A thousand values, ten looks.

Activity 34, Problem 2: BST, heap, both, or neither?

See Problem 2 on Activity 34.

Answer.

  • A: search tree only. Left of 10 is 5, 1, 7 and right is 15, 12. Not a heap: 15 is bigger than its parent
  • B: max-heap only. Complete, and every parent is >= its children. Not a search tree: 40 is in the right subtree of 50, and 40 < 50
  • C: both. 5 < 9 for the search tree, 9 >= 5 for the heap, and one left child keeps it complete
  • D: neither. 15 > 10 breaks the heap. 12 is fine next to 5, but it's in the left subtree of 10 and 12 > 10. The search-tree rule is about every ancestor

Could C get a third node and stay both? No. A right child would have to be bigger than 9 for the search tree and at most 9 for the heap. A child under 5 breaks completeness, since row 2 isn't full.

Search, in code

fn contains(tree: &Option<Box<Node>>, target: i32) -> bool {
    match tree {
        None => false,                           // fell off the bottom
        Some(node) => {
            if target == node.value {
                true
            } else if target < node.value {
                contains(&node.left, target)     // check if it's on the left
            } else {
                contains(&node.right, target)    // check if it's on the right
            }
        }
    }
}

Same shape as len: None is the base case, Some recurses. One extra decision per node: which child.

Insert: 5 arrives. Where does it go?

         8
        / \
       3   10
      / \    \
     1   6    14
        / \   /
       4   7 13

There's exactly one spot that keeps the BST property. How do you find it?

Insert: search, then fill the hole

         8                5 < 8: left
        / \
       3   10             5 > 3: right
      / \    \
     1   6    14          5 < 6: left
        / \   /
       4   7 13           5 > 4: right. Nothing there: put it there
        \
         5

A new value is always a new leaf. Every insert is one Box::new, one new block on the heap, and a pointer in the parent that was None is now Some.

Cost: the same walk as search, O(height).

Where it lives: the tree

let mut tree: Option<Box<Node>> = None;
insert(&mut tree, 8);
insert(&mut tree, 3);
insert(&mut tree, 10);
Stack:                             Heap:
┌───────────────────────────┐      ┌──────────────────┐
│ main()                    │      │ value: 8         │      ┌──────────────────┐
│ └ tree: Option<Box<Node>> │      │ left: Some(Box)  │      │ value: 3         │
│    = Some(ptr) ───────────┼─────▶│   └ ptr ─────────┼─────▶│ left: None       │
└───────────────────────────┘      │ right: Some(Box) │      │ right: None      │
                                   │   └ ptr ─────────┼──┐   └──────────────────┘
                                   └──────────────────┘  │   ┌──────────────────┐
                                                         └──▶│ value: 10        │
                                                             │ left: None       │
                                                             │ right: None      │
                                                             └──────────────────┘

Three nodes, three blocks, two pointers out of the root.

Monday's tree and today's

They're both "trees" but have different memory layouts and different jobs.

BinaryHeap (Monday)Search tree (today)
ShapeComplete, no gapsAny shape
MemoryOne blockOne block per node
Find a childArithmetic, 2i + 1Follow a pointer
Biggestpeek, O(1)Keep going right, O(height)
Is x in here?O(n), look at everythingO(height)
InsertO(log n), bubble upO(height), fill the hole
Everything in orderSort it, O(n log n)Left, node, right: O(n)

When the tree is a list

"O(height)" is only good news when the tree is bushy.

Watch what happens if we insert 1, 2, 3, 4, 5, 6, then 7:

   1
    \
     2
      \
       3            Every insert went right. Height 7.
        \           Search is O(n) again: it's a linked list!
         4
          \
           5
            \
             6
              \
               7

Real search trees rebalance themselves as they go, so height stays . Rust's BTreeMap and BTreeSet do that for you, and they're the sorted cousins of HashMap and HashSet. See the appendix.

The game tree

Project 3's minimax is a tree search too. Every position is a node, with one child for every legal move. The root is the board right now. The leaves are finished games.

                   [current board]              X to move: take the max
                  /       |        \
            [X top]   [X middle]  [X bottom]    O to move: take the min
             / \         / \         / \
           ...  ...    ...  ...    ...  ...     ...until the game ends

search is like len with a score instead of a count: a base case at the bottom, a recursive call per child, and the answer bubbles up.

One difference from everything else today: this tree is never stored. There's no Node and no Box. apply_move steps into a child, the recursive call explores it, and undo steps back out. The tree exists only (implicitly) in the call stack.

This week's structures

NeedUseUnder the hood
Pop the newestVecOne block
Pop the oldestVecDequeOne block, a head, % cap
Pop the biggestBinaryHeapOne block, (i - 1) / 2
Is this here?HashSetOne block of buckets, hash % buckets
Keep it sorted while it changesA search tree, BTreeSetOne block per node, joined by pointers
Look ahead in a gameA game treeNever stored. Recursion walks it

Key takeaways

  • A type that holds itself has no size. Option<Box<Node>> gives it one: a pointer, or nothing
  • One block per node. A list of a thousand is a thousand allocations, and the blocks can be anywhere
  • A recursive type gets a recursive function: None is the base case, Some recurses
  • A binary search tree keeps left < node < right at every node. Search and insert are O(height): one comparison per row, and insert is a failed search that fills the hole
  • Monday's heap is one block and arithmetic. Today's tree is pointers. Same picture, two layouts

Activity 34

See Activity 34. Problems 1 and 2 are done, so start at Problem 3.

Appendix: the search tree as a whole program

struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

fn contains(tree: &Option<Box<Node>>, target: i32) -> bool {
    match tree {
        None => false,
        Some(node) => {
            if target == node.value {
                true
            } else if target < node.value {
                contains(&node.left, target)
            } else {
                contains(&node.right, target)
            }
        }
    }
}

fn insert(tree: &mut Option<Box<Node>>, value: i32) {
    match tree {
        None => *tree = Some(Box::new(Node { value, left: None, right: None })),
        Some(node) => {
            if value < node.value {
                insert(&mut node.left, value)
            } else {
                insert(&mut node.right, value)
            }
        }
    }
}

fn smallest(tree: &Option<Box<Node>>) -> Option<i32> {
    match tree {
        None => None,
        Some(node) => match &node.left {
            None => Some(node.value),        // nothing to the left: this is it
            Some(_) => smallest(&node.left), // keep going left
        },
    }
}

fn main() {
    let mut tree: Option<Box<Node>> = None;
    for v in [8, 3, 10, 1, 6, 14, 4, 7, 13] {
        insert(&mut tree, v);
    }
    println!("{} {}", contains(&tree, 6), contains(&tree, 11));   // true false
    println!("{:?}", smallest(&tree));                             // Some(1)
}

In insert, the None arm is the only place a node is made: *tree = ... writes through the &mut and fills the hole in the parent. Equal values go to the right, so duplicates are allowed and contains still finds them. Many search trees refuse duplicates instead; BTreeSet does.

Appendix: delete, the tricky one

Search and insert only ever touch a leaf. Delete can hit a node in the middle, and there are three cases:

  1. No children. Set the parent's pointer to None. The block is freed when the Box drops
  2. One child. Point the parent at the child instead. The subtree under the child comes along
  3. Two children. Find the in-order successor, the smallest value in the right subtree (go right once, then left until you can't). Copy its value into the node, then delete the successor, which has at most one child, so it's case 1 or 2
Delete 3:
         8                     8
        / \                   / \
       3   10                4   10        4 is the smallest value to
      / \    \     ->       / \    \       the right of 3, so it keeps
     1   6    14           1   6    14     1 < 4 < 6, 7
        / \   /               \   /
       4   7 13                7 13

Still O(height). In Rust the Option<Box<Node>> juggling for case 3 is fiddly enough that it's a good exercise and a bad lecture slide.

Appendix: balance, and Rust's BTreeMap

A tree built from sorted input is a list, and every operation is O(n). Self-balancing trees fix the shape as they insert, so height stays O(log n):

  • AVL trees keep the two sides of every node within one row of each other
  • Red-black trees allow a little more lean for cheaper inserts
  • B-trees put many values in each node, so each block holds a whole row. Databases and file systems use them, because reading one block from disk costs the same whether it holds one value or a hundred

Rust's sorted collections are B-trees: BTreeSet<T> and BTreeMap<K, V>. Same API as HashSet and HashMap, plus everything comes out in order, and you can ask for a range:

use std::collections::BTreeMap;

fn main() {
    let mut wins = BTreeMap::new();
    wins.insert("Celtics", 48);
    wins.insert("Bucks", 51);
    wins.insert("Knicks", 47);

    for (team, w) in &wins {              // alphabetical, always
        println!("{}: {}", team, w);
    }
    for (team, w) in wins.range("B".."D") {   // just the B's and C's
        println!("{}: {}", team, w);
    }
}

The trade: HashMap is O(1) per lookup and unordered. BTreeMap is O(log n) and sorted. Pick by whether you ever need things in order.

Appendix: why not a sorted Vec?

A sorted Vec finds things by binary search in O(log n) too, and it's one block. The difference is what happens when the data changes:

OperationSorted VecBalanced search tree
SearchO(log n)O(log n)
InsertO(n), shift everything after itO(log n)
DeleteO(n), sameO(log n)
SmallestO(1), index 0O(log n), keep going left

Wednesday's remove(0) all over again. If the data is built once and searched many times, sort a Vec. If it keeps changing, use the tree.