Lesson contents

Binary search trees

In a binary search tree, smaller keys go left and larger keys go right. Each comparison rules out an entire branch.

Simple example

Start at 8 and search for 12. Since 12 is larger, follow the right link. Print the key you find.

Start8→3,12
Result12
lesson.mojo
def main():
    var keys: List[Int] = [8, 3, 12]
    var left: List[Int] = [1, -1, -1]
    var right: List[Int] = [2, -1, -1]
    var wanted = 12
    var node = 0
    while node != -1:
        if wanted == keys[node]:
            print(keys[node])
            break
        if wanted < keys[node]:
            node = left[node]
        else:
            node = right[node]
Output
12
Advertisements

Everyday examples

Find a library catalogue number

The root card is 50, with cards 30 and 70 to its left and right. Which card do you inspect after 50 when looking for 30?

Start50→30,70
Result30

Compare 30 with 50 and follow the left branch. The 70 branch cannot contain 30.

File a new ticket

Tickets 20, 10 and 35 form a search tree rooted at 20. Where does ticket 28 go?

Start20→10,35
Result35←28

Go right from 20 and then left from 35. The new ticket belongs at that empty link.

Read keys in sorted order

A tree stores 9 at the root, 4 on the left and 12 on the right. Which walk gives ascending order?

Start9→4,12
Result4 9 12

Visit the left subtree, then the root, then the right subtree. The ordering rule makes the result sorted.

Cost and limits

Searching takes time proportional to the tree height. Inserting sorted keys into an ordinary unbalanced tree can produce a long chain. Choose a duplicate-key policy explicitly.