Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
Emma's seven number cards stored as a binary search tree: smaller goes left, bigger goes right, so 60 is found in 3 looks instead of 6. Insert and search step by step, a million cards answered in 15 looks, and the sorted input that turns the tree into a stick.
What you will learn
- Explain the binary search tree rule with the higher-or-lower guessing game
- Insert values and search a tree by walking one path down
- Say why a well-shaped tree needs about log n looks, and why sorted input turns it into a stick
- Read a small Python Node and NumberTree with insert and contains
Before you start
- Big-O: Reading Cost From Code
- Recursion
Emma has a box of number cards: 50, 30, 70, 20, 40, 60 and 80. They arrive in no order at all. Jack asks: is 60 there? Checking card by card, 60 turns up on look number six. And 65? All seven looks, and still no.
We want every look to throw away half of the cards, so 60 is found in three looks and 65 is ruled out in three looks too. That's exactly what a binary search tree does.
Higher or lower
Think of the guessing game. Emma hides one card, and after every guess she only says "higher" or "lower".
- Guess one is 50, right in the middle. "Higher!" So 20, 30 and 40 are out in one go.
- Guess two is 70. "Lower!" So 80 is out too.
- Guess three is 60. Yes. Three guesses, not seven.
Now draw the guesses as a map. 50 is at the top. Lower means go left, higher means go right. Store the cards like this map, and you have a binary search tree.
Insert, then search, step by step
Start with an empty tree and the seven cards waiting.
- 50 comes first. The tree is empty, so 50 becomes the root, the top card.
- 30 is smaller than 50, so go left. Left of 50 is empty, so 30 goes there.
- 70 is bigger, so it goes right of 50.
- 20: smaller, smaller, so left of 30.
- 40: smaller than 50, bigger than 30, so right of 30.
- 60 goes left of 70, and 80 goes right of 70.
Seven cards, just three levels. Now search for 60 from the root: bigger than 50, go right; smaller than 70, go left; equals 60, found after three looks. For 65: right at 50, left at 70, and at 60 it's bigger, but 60 has nothing on its right. So 65 isn't there, and you knew after three looks.
That empty spot is useful, too. It's the very spot where 65 would go if you inserted it. And one walk down answers more than yes or no: keep going left and you stop at the smallest card, 20; keep going right and you stop at the biggest, 80.
Why it's fast: each level doubles the room
Three levels hold seven cards, so the most you ever look at is three. Every new level doubles the room: 7 cards, then 15, then 31. Ten levels hold 1,023, and twenty levels hold over a million. So a well-shaped tree with a million cards needs at most about twenty looks. A plain list may need all one million. Each look goes one level down and throws away about half: that's O(log n).
Cards that arrive sorted
Same rule, but now the cards arrive already sorted: 10, 20, 30 up to 70. 10 becomes the root. 20 is bigger, so it goes right. 30 is bigger than both, so right again. Every card goes right. Seven cards, seven levels: the tree has become a stick.
Searching for 70 now goes right, right, right all the way down: seven looks for seven cards. Every look threw away only one card, so it's no better than checking card by card. Put the same seven cards in a better order (40 first, then 20 and 60, then the rest) and the tree is short and wide again, three looks. Real software knows this: a balanced tree rebalances itself, turning a few cards around whenever one side grows too tall.
The code
Here's the small brick the tree is built from:
class Node:
def __init__(self, value):
self.value = value
self.left = None # smaller values go here
self.right = None # bigger values go here
A new node starts with no children. Every node points to at most two others, which is why it's called a binary tree. The tree itself:
from node import Node
class NumberTree:
def __init__(self):
self.root = None
self.looks = 0 # nodes checked by the last search
def insert(self, value):
self.root = self._insert(self.root, value)
def _insert(self, node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = self._insert(node.left, value)
else:
node.right = self._insert(node.right, value)
return node
def contains(self, value):
self.looks = 0
node = self.root
while node is not None:
self.looks += 1
if value == node.value:
return True
node = (node.left if value < node.value
else node.right)
return False
_insert asks: is this spot empty? Then the new card goes here. Otherwise smaller goes left and bigger goes right, and it calls itself on that side (that's recursion). contains walks down from the root, adding one to looks at every node, until it finds the value or reaches None. Insert and search ask the same question at every node: smaller or bigger?
from number_tree import NumberTree
tree = NumberTree()
cards = [50, 30, 70, 20, 40, 60, 80]
for card in cards:
tree.insert(card)
print("Is 60 there? " + str(tree.contains(60)).lower()
+ ", looks: " + str(tree.looks))
print("Is 65 there? " + str(tree.contains(65)).lower()
+ ", looks: " + str(tree.looks))
Is 60 there? true, looks: 3
Is 65 there? false, looks: 3
A million cards
import random
from number_tree import NumberTree
for n in (100, 10_000, 1_000_000):
cards = list(range(1, n + 1))
random.Random(457).shuffle(cards) # mixed up
tree = NumberTree()
for card in cards:
tree.insert(card)
tree.contains(n + 1) # not there
print(f"{n:9,d} cards: {tree.looks} looks to say no")
100 cards: 6 looks to say no
10,000 cards: 9 looks to say no
1,000,000 cards: 15 looks to say no
With a million shuffled cards, this tree says no after 15 looks. A list would check all one million.
And the stick, in code
from number_tree import NumberTree
tree = NumberTree()
for card in range(10, 71, 10):
tree.insert(card) # the cards arrive sorted
print("Is 70 there? " + str(tree.contains(70)).lower()
+ ", looks: " + str(tree.looks))
Is 70 there? true, looks: 7
The cost
| Operation | Cost | Why |
|---|---|---|
| Insert (well-shaped tree) | O(log n) | one path down to the empty spot |
| Search (well-shaped tree) | O(log n) | each look throws away about half |
| Search a plain list | O(n) | card after card |
| Search after sorted inserts | O(n) | the tree is a stick |
Where you meet search trees
- Databases find a record fast with a tree cousin of this idea, so they don't read the whole table.
- Many languages keep a sorted map or set as a search tree that levels itself.
- Linux keeps the jobs waiting for the processor in a tree, so it can find the next one fast.
- Range questions, like every price from 30 to 60: find 30, then walk on in order. Walking in order is the subject of tree traversals.
Try it yourself
Add a min method to NumberTree that keeps going left until there is no left child, and print the smallest card. You should get 20.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
