Binary search trees, step by step
A contact list must stay A→Z, find anyone instantly and take new contacts all day. Watch a sorted array buckle, grow a tree, see it fall over into a line, and fix it.
3 steps · about 6 minutes · free, no sign-up
Step 1: Keep it sorted
Contacts in a sorted array: binary search finds anyone in about 20 checks.
But adding "Eve" shifts every later name one place: 700,000 moves.
Contacts must stay in A→Z order, be found fast, and new ones arrive all day. A sorted array makes every insert shift hundreds of thousands of names. What do you do?
- Use a hash table (Helps for a while): Finding and adding are instant. But a hash table keeps no order, and the contacts screen must show A→Z, so you would sort a million names every time someone scrolls.
- Store them in a binary search tree (Right fix): Each name keeps smaller names on its left and bigger ones on its right. To add Eve you walk down (Kim → Dev → Fay) and hang her in the empty spot. Nothing shifts. Binary search tree: A tree where every node’s left side holds smaller keys and its right side bigger ones. Find, add and remove follow one path from the root: O(log n) when the tree is balanced, about 20 steps for a million items.
- Use a sorted linked list (Not this one): Inserting needs no shifting, but finding where Eve belongs means walking the list from the start, hundreds of thousands of steps. Finding a contact is just as slow.
Step 2: Importing an A→Z file
Imported A→Z: every new name is bigger, so it always goes right…
…the tree is now one long line: a million names means a million checks.
Contacts imported from an A→Z file are each bigger than the last, so every one goes right. The tree has become a long line. What do you do?
- Buy a phone with more memory (Not this one): Memory isn’t the problem: the shape is. A line-shaped tree needs a step per name, however much memory you have.
- Shuffle the file before importing (Helps for a while): Random order usually gives a bushy tree, so it helps. But nothing guarantees it, and contacts added later in order can stretch it out again.
- Use a self-balancing tree (Right fix): After each insert, the tree checks its shape and rotates a few links so no side gets too deep. It stays about 20 levels deep for a million names, whatever order they arrive in. Self-balancing tree: A binary search tree that fixes its own shape with small rotations after inserts and deletes (AVL and red-black trees). Height stays O(log n), so every operation stays fast. Java’s TreeMap and C++’s std::map are red-black trees.
Step 3: Names from K to N
Back to the full contact list, kept balanced.
Now: show every name from K to N.
The app shows a scrolling index: tap “K” and it lists every contact from K to N. What is the fast way?
- Look up every contact by hashing (Not this one): Hashing finds one exact name. It can’t answer “everything between K and N” without checking every contact.
- Find K, then walk the tree in order until N (Right fix): Walk down to where K would be (about 20 steps), then visit nodes in order, left to right, stopping after N. You touch only the names you show, plus a short path. In-order traversal and range queries: Visiting a BST left, node, right gives keys in sorted order. A range query finds the start, then walks in order to the end: O(log n + k) for k results. Databases use the same idea in B-tree indexes.
- Check every contact and keep the K–N ones (Helps for a while): It always works and is simple, fine for a few hundred contacts. With a million, every tap checks a million names.
What you learned
- Binary search tree: Smaller keys left, bigger keys right, so find and insert follow one path down.
- Height: The number of levels decides the speed: about 20 for a million names when balanced, a million when it is a line.
- Self-balancing: AVL and red-black trees rotate links after changes to keep the height O(log n).
- In-order traversal: Left, node, right visits keys in sorted order, which makes range queries fast.
| Operation | Sorted array | Hash table | Balanced BST |
|---|---|---|---|
| Find | O(log n) | O(1) average | O(log n) |
| Insert | O(n) | O(1) average | O(log n) |
| List in order | O(n) | O(n log n) (sort first) | O(n) |
| Range K to N | O(log n + k) | O(n) | O(log n + k) |
An unbalanced BST degrades to O(n) for everything. Use a library’s balanced tree (Java TreeMap, C++ std::map) rather than writing your own.
In code
class Node:
def __init__(self, key):
self.key, self.left, self.right = key, None, None
def insert(root, key): # O(height)
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def in_order(root): # sorted order
if root:
yield from in_order(root.left)
yield root.key
yield from in_order(root.right)
root = None
for name in ["Kim", "Dev", "Raj", "Bo", "Fay", "Eve"]:
root = insert(root, name)
print(list(in_order(root))) # ['Bo', 'Dev', 'Eve', 'Fay', 'Kim', 'Raj']- Lesson: why hash tables exist
- Lesson: arrays vs linked lists
- Interview pattern: binary search
- Read: binary search trees explained
Frequently asked questions
What is a binary search tree?
A tree where each node’s left subtree holds smaller keys and its right subtree bigger keys, so you can find or insert a key by following one path down.
Why does a BST need balancing?
If keys arrive in sorted order, every new key goes the same way and the tree becomes a line, making operations O(n). Self-balancing trees rotate links to keep the height O(log n).
BST or hash table?
Use a hash table for fast lookup by exact key. Use a balanced BST when you also need order: sorted listing, smallest or largest key, or ranges.
What is in-order traversal?
Visiting the left subtree, then the node, then the right subtree. In a BST it lists the keys in sorted order.