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

Activity 34: Trees on paper

Name:

Problem 1: draw a list (in lecture)

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

let b = Node { value: 9, next: None };
let a = Node { value: 5, next: Some(Box::new(b)) };
let list: Option<Box<Node>> = Some(Box::new(a));
  1. Draw the stack and the heap. Label every block.
  2. How many blocks are on the heap? How many would a list of a thousand nodes need?
  3. What does len(&list) return, and how many times does len get called?





















Answer.

Stack:                            Heap:
┌─────────────────────────────┐   ┌──────────────────┐   ┌──────────────────┐
│ main()                      │   │ value: 5         │   │ value: 9         │
│ └ list: Option<Box<Node>>   │   │ next: Some(Box)  │   │ next: None       │
│    = Some(ptr) ─────────────┼──▶│   └ ptr ─────────┼──▶│                  │
└─────────────────────────────┘   └──────────────────┘   └──────────────────┘
  1. Two blocks, one per node. A thousand nodes is a thousand blocks. Monday's BinaryHeap of a thousand was one block
  2. 2. len is called three times: on the 5, on the 9, and on the None at the end, which returns 0

Problem 2: BST, heap, both, or neither? (in lecture)

Tree A:          Tree B:          Tree C:        Tree D:
    10              50               9              10
   /  \            /  \             /              /  \
  5    15        30    40          5              5    15
 / \   /        /  \                             / \
1   7 12      10   20                           1   12
  1. For each tree: a search tree, a max-heap, both, or neither? Give the reason in a few words.
  2. Tree C is small. Could you add a third node and keep it both? Where, or why not?






Answer.

  1. 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.
  2. 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 yet. "Both" tops out at two nodes.

Problem 3: trace a search and an insert

Start from this search tree. For each task, list the nodes you visit, in order.

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

a. contains(&tree, 4). Which nodes, and what comes back?

b. contains(&tree, 11). Which nodes, and what comes back?

c. insert(&mut tree, 11). Which nodes, and where does 11 end up? Draw the tree after.













Answer.

a. 8 (4 is smaller, go left), 3 (bigger, go right), 6 (smaller, go left), 4. Found: true

b. 8 (right), 10 (right), 14 (left), 13 (left), then None. Not there: false

c. The same path as part b: 8, 10, 14, 13, then None to the left of 13. That's where the search fell off, so that's where 11 goes, as a new leaf:

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

Problem 4: read one, write one

a. Here's len for the list, from lecture. Write sum for the tree: the total of every value in it.

fn len(list: &Option<Box<Node>>) -> usize {
    match list {
        None => 0,
        Some(node) => 1 + len(&node.next),
    }
}

fn sum(tree: &Option<Box<Node>>) -> i32 {













}

What does sum return for the tree in Problem 3? What's its Big-O, for n nodes?


Answer.

fn sum(tree: &Option<Box<Node>>) -> i32 {
    match tree {
        None => 0,
        Some(node) => node.value + sum(&node.left) + sum(&node.right),
    }
}

66 for Problem 3's tree. O(n): every node is visited exactly once, and there's no comparison to let us skip a subtree. Adding things up needs all of them.

b. Starting from an empty tree, insert 5, 4, 3, 2, 1 in that order. Draw the result. What's the height, and what does searching it cost?













Answer. Every value is smaller than the one before, so every insert goes left:

        5
       /
      4
     /
    3
   /
  2
 /
1

Height 5, for 5 nodes. It's a linked list leaning the other way from the lecture's, and search is O(n) just the same. This is why real search trees rebalance (see the lecture appendix on BTreeMap).

Problem 5: which structure?

For each one, pick BinaryHeap, a binary search tree (BTreeSet), or HashSet, and say in a few words why.

  1. A game server runs thousands of scheduled events. Every tick, it runs whichever is soonest.
  2. A card game keeps every card still in the deck, and needs to deal "the lowest card above a 7" and "the three highest cards" quickly, as the deck changes.
  3. Dealing cards: before handing one out, check whether it's already been dealt this hand.



Answer.

  1. BinaryHeap. Just the "what's next?" question asked over and over, O(log n) per push and pop
  2. A binary search tree. Both questions are about order, "above a 7" is a range, and the deck keeps changing, so a sorted Vec would cost O(n) per deal
  3. HashSet. Just "is this in here?" and nobody cares about order