Skip to content

How a binary search tree stays searchable

Working knowledgeUnder the hood

A binary search tree finds a key among a million in about twenty comparisons, or takes a million. Here is the rule that makes it fast, and the insert order that quietly breaks it.

01 The rule: left smaller, right bigger

Each node holds a key and up to two children. The rule is about whole subtrees, not just children: every key anywhere below a node's left side is smaller than it, and every key below its right side is bigger.

That one rule means that at any node you know which half the key you want must be in. You never have to look at the other half.

Each parent and child pair looks fine, but the tree breaks the rule
Not a binary search tree
8
3
1
9> 8
10
  • in the wrong subtree
  • the bound it breaks

9 is bigger than its parent 3, so as 3's right child it looks right. But it sits in 8's left subtree, where every key must be smaller than 8. A search for 9 would turn right at 8 and never find it.

02 Insert: search, then fill the empty slot

To insert a key, search for it. The search ends at an empty slot, because the key is not there yet, and that slot is exactly where the key belongs. Existing nodes never move.

Building a tree one insert at a time
Step 1 of 10
Comparisons 0
Binary search treeEmpty
  • compared on the way
  • just inserted

The tree starts empty. The keys will arrive in this order: 8, 3, 10, 1, 6, 14, 4, 7, 13.

— inserting

The output shows the bonus: an in-order walk (left, node, right) of a binary search tree gives the keys sorted. That follows directly from the rule.

04 The code

Search is a loop that walks down. Insert is the same walk, written recursively so each parent can attach the new child on the way back.

bst.py
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def search(node, key):
while node is not None and node.key != key:
node = node.left if key < node.key else node.right
return node # None when the key is not in the tree
def insert(node, key):
if node is None:
return Node(key) # an empty slot: the key goes here
if key < node.key:
node.left = insert(node.left, key)
main.py
root = None
for key in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
root = insert(root, key)
print(search(root, 7).key)
print(search(root, 5))
Text
7
None

05 When the tree goes skewed

The work is one comparison per level, so the cost is the tree's height. The shape depends only on the insert order. Insert keys that are already sorted, and each new key is bigger than everything so far: it always goes right, and the tree becomes a linked list.

Sorted inserts build a chain
Keys 1 to 5 inserted in order
1
2
3
4
55 compares
  • deepest key

Every node has only a right child. Searching for 5 compares against all five keys, exactly like scanning a list.

Balanced, 1,000,000 keysAbout 20 levelsEach level doubles how many keys fit, and 2 to the power 20 is just over a million. Search, insert and delete take about 20 steps.
Sorted inserts, 1,000,000 keys1,000,000 levelsOne key per level. Every search for a large key walks the whole chain, and building the tree costs about n²/2 comparisons in total.

This is why library ordered maps use self-balancing trees, which rotate nodes after inserts and deletes to keep the height near log₂ n. Java's TreeMap is a red-black tree, and C++ std::map is typically one too. Python has no built-in tree map; dict is a hash table.

06 When it bites

node.left.key < node.keyChecking only parent and childThe broken tree above passes this check at every node. Pass the allowed range down instead: the left side gets an upper bound, the right side a lower bound.
for k in range(1, 2001): root = insert(root, k)Sorted input and recursionThe chain gets one level deeper per key. In CPython the recursive insert raises RecursionError once the depth passes the default limit of about 1,000.
insert(root, 6) # againDuplicate keysDecide once: ignore them (as above), keep a count in the node, or always send equal keys the same way. Mixing rules breaks search.
delete(root, 3)Deleting a node with two childrenYou cannot just remove it. Copy in its in-order successor, the smallest key in its right subtree, then delete that node, which has at most one child.

07 Check yourself

Question

You insert 5, 2, 8, 1 into an empty tree, then insert 3. Where does 3 go?

Question

Root 10 has left child 5, and 5 has right child 12. Is this a binary search tree?

Question

You insert the keys 1 to 7 in increasing order. How many keys does a search for 7 compare against?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?