Intermediate 8 min

Binary search trees

A binary search tree stores smaller keys on the left and larger keys on the right, with an explicit rule for duplicates.

How it works

At every node, you choose one subtree according to the ordering rule. Count the nodes examined, which depends on tree height. Inserting already sorted keys into a plain tree can create a long chain. A balanced tree keeps comparable branches available so searches need fewer decisions.

Walk through an example

From root 8, searching for 5 goes left. At node 3, 5 is larger, so it goes right. Each comparison rules out an entire subtree.

What to watch for

A chain-shaped tree can take linear time. Logarithmic search needs a tree with height proportional to the logarithm of its size.

Code example

def contains(root, key):
    while root is not None:
        if root.key == key: return True
        root = root.left if key < root.key else root.right
    return False

Check your understanding

Which keys are visited when searching for 5?

See the example and explanation
Worked example
Given Root 8, left child 3, right child 10, and 3 has right child 5.
Answer 8 → 3 → 5

At 8, go left because 5 is smaller. At 3, go right because 5 is larger.

Open practice problem
Next lessonAlgorithm invariants