Code

The walk, the range, the height — write them yourself

Put works. The remaining five functions — the walk, the range, minimum, maximum and height — come without holes this time: empty skeletons, and you fill them in completely.

You have already seen all of them in the last step's tables. Below are the same tables written as pseudocode.

The in-order walk (Keys)

Step 2's answer, in three lines:

walk(n):
    if n = nil: return
    walk(n.left)      // first everything smaller
    output n.key      // then me
    walk(n.right)     // then everything larger

It follows straight from the invariant: the left subtree is all the smaller keys, so outputting them first, then yourself, then all the larger ones gives ascending order. O(n), no extra memory and not a single comparison.

Keys takes no counter — and should not. Every node is visited once, and no key is compared with another.

A range query (Range)

The same walk, with two conditions that cut off unneeded branches:

Range(lo, hi, n):
    if n = nil: return
    c.Hit()                                             // you entered a node
    if lo < n.key:            Range(lo, hi, n.left)     // the left may hold some
    if lo ≤ n.key ≤ hi:       output n.key
    if n.key < hi:            Range(lo, hi, n.right)    // the right may hold some

Those two ifs are what turned step 1's 1,000 nodes into 11, and the last step's table's 6 nodes into 3: once n.key is already larger than hi, there cannot be an answer anywhere in the right subtree, so it is not even entered.

A hash table cannot make that decision. It does not know what "larger" means.

c.Hit() — once per node you enter, not once per comparison. That is how the last step's table was counted (Emma .. Hamlet — 3 of 6), and the test checks the same number.

Min, Max and Height

Min():                          Max():
    if root = nil: none             if root = nil: none
    n ← root                        n ← root
    while n.left ≠ nil:             while n.right ≠ nil:
        n ← n.left                      n ← n.right
    return n.key                    return n.key

Height(n):
    if n = nil: return 0
    return 1 + max(Height(n.left), Height(n.right))

Height counts nodes, not edges. An empty tree is 0, a single node is 1. Step 8's table rests on that definition.

Recursion is natural here: Keys, Range and Height are described in terms of themselves, like lesson 5's walks. Min and Max are plain loops — recursion buys them nothing.

Your job

bst.go (in the panel) has grown: five new skeletons, Keys, Range, Min, Max and Height, each with panic("not implemented").

Put still shows up in the panel with its holes — the panel shows the skeleton, not your file. In your copy they are already filled in; leave them that way.

Read the contracts, not just the signatures. The doc comments state everything the test will check.

bst_test.go has grown too. It now checks eight things:

test what it demands
TestTreeStoresAndFinds finds everything stored, does not find what was not
TestTreeDuplicateKeysReplace an equal key replaces (as in lesson 10)
TestTreeReproducesTheLessonTrace step 2's tree: shape, cost of insertion and lookup
TestLessonTreeWalksAndRanges the same six: walk, Min/Max, height 3, range Emma .. Hamlet — 3 of 6
TestKeysComeBackSorted Keys() IS sorted; Min/Max match the ends
TestRangeReturnsOnlyTheBand the range returns only its band and visits fewer than all nodes
TestShuffledInsertStaysLogarithmic on shuffled input the depth stays logarithmic
TestSortedInsertDegeneratesIntoAList on sorted input Height() == n

TestKeysComeBackSorted looks familiar — and it should. In lesson 10 the test demanded that Keys() was not sorted, because a hash index cannot promise order. Here it demands that it is. The same test, the opposite sign: two promises, two structures.

The last one is a defect-asserting test again, like lesson 7's selection sort, lesson 8's quicksort and lesson 9's unstable pass. It demands that sorted insertion gives a tree of height exactly n.

If it ever starts failing — you have built something other than a plain BST. In lesson 12 you will do exactly that, on purpose; until then it protects step 8's demonstration.

Run the test

While Keys is empty, the test blows up at the first walk:

$ go test ./...
--- FAIL: TestLessonTreeWalksAndRanges (0.00s)
panic: not implemented [recovered, repanicked]
...
algo.(*TreeIndex).Keys(...)

That is not an error — it is a pointer to what to write first. Fill the functions in order.

When it does not pass

  • Keys() = [Hamlet Dune Beloved Emma Ulysses Lolita] — you output yourself before the left subtree. The order has to be left, me, right.
  • Range(Emma, Hamlet) = [Emma Hamlet] after 6 visits, want ... after 3 and visited 1000 nodes for a 10-key range — the walk is not pruning — the result is right, but you walked the whole tree. Both ifs (lo < n.key and n.key < hi) must guard the recursive calls.
  • ... after 2 visits, want ... after 3 — you are counting the wrong thing: c.Hit() goes once when you enter a node, not only when it lands in the range.
  • Height() = 2, want 3 — you are counting edges, not nodes: a leaf must be 1, and an empty place 0, not -1.