You insert sorted keys into a BST. Why does it get slow?
Question
An order service keeps order ids in a plain binary search tree (BST). It never rebalances the tree. Smaller keys go left, larger keys go right.
Ids grow by one: 1, 2, 3, and so on. After 2,000 orders, lookups are slow. A recursive function that prints all orders in id order crashes with RecursionError.
- What shape is the tree, and how tall is it?
- How many key comparisons did it take to build?
- Why does the recursive function crash?
- What would you use instead?
Show hints (3)
- "DRAW FOUR KEYS"
Insert 1, 2, 3, 4 into an empty BST by hand. What shape do you get?
- "COUNT THE STEPS"
The third id is compared with the two keys before it. The kth id is compared with k - 1 keys. Add that up for 2,000 ids.
- "HOW DEEP"
A recursive walk makes one call per level. How many levels does the tree have? Compare that with
sys.getrecursionlimit().
Show checked explanation
Each new id is the largest so far, so it always goes right. The tree becomes a chain 2,000 levels tall, and search and insert are O(n), not O(log n). Building it took 1,999,000 comparisons. A recursive walk needs 2,000 nested calls, past Python's default limit of 1,000. Use a self-balancing tree, or a dict or sorted list.
import random def height_after_inserts(keys): root, height = [keys[0], None, None], 1 # a node is [key, left, right] for key in keys[1:]: node, depth = root, 2 side = 1 if key < node[0] else 2 while node[side] is not None: node, depth = node[side], depth + 1 side = 1 if key < node[0] else 2 node[side] = [key, None, None] height = max(height, depth) return height ids = list(range(1, 2001)) print("sorted:", height_after_inserts(ids)) random.Random(1).shuffle(ids) print("shuffled:", height_after_inserts(ids))
sorted: 2000 shuffled: 24
Code run on CPython 3.12. Checked by an editor other than the author.
Walkthrough
Insert 1, 2, 3, 4 into an empty BST. 1 becomes the root, 2 goes right of 1, and 3 goes right of 2. Each new id is the largest so far, so it always lands at the bottom right:
1
\
2
\
3
\
4It is really a linked list. With 2,000 sorted ids, the tree is 2,000 levels tall.
| insert order | height | comparisons to build |
|---|---|---|
| sorted, 1 to 2,000 | 2,000 | 1,999,000 |
| random order | usually 22 to 28 | about 24,700 on average |
The kth id is compared with all k - 1 keys before it. In total that is 0 + 1 + ... + 1,999 = 1,999,000 comparisons. A search for the newest order visits all 2,000 nodes. Each operation is O(h), where h is the height, and here h = n.
The best possible height for 2,000 keys is 11, because 11 full levels hold 2,047 keys. A balanced tree needs about 11 steps per search, not 2,000.
The crash has the same cause. A recursive inorder print goes one call deeper per level, so 2,000 calls deep. Python's default recursion limit is 1,000 (sys.getrecursionlimit()), so it raises RecursionError. The code above uses a loop, so it doesn't crash, but it is still slow.
So the insert order is the problem. In random order, the height grows like log n. The code's one shuffle gives height 24.
Common mistakes
- Saying BST operations are O(log n). That is true only while the tree stays balanced. A plain BST costs O(h), and h can be n.
- Fixing the crash with
sys.setrecursionlimit(10_000). The tree is still a chain, so every operation is still O(n). A limit that is too high can also crash Python itself. - Using a shuffle as the fix for live data. A shuffle needs all keys up front, but orders arrive one at a time, with growing ids.
- Thinking descending ids are safe. Inserting 2,000 down to 1 builds the same chain, just going left.
Follow-up questions
- "How does an AVL or red-black tree keep the height low?" After each insert or delete, it walks back up. Where one side got too tall, it rotates a few nodes. The keys stay in BST order. At worst, a large AVL tree is about 1.44 times as tall as a perfect one. A red-black tree with n keys has at most 2 log₂(n + 1) levels. Both give O(log n).
- "Python has no built-in balanced tree. What do you use?" For lookups by id, a
dictis O(1) on average. For ids that only grow, append them to a list. It stays sorted,appendis amortized O(1), andbisectfinds an id or a range in O(log n). Inserting in the middle of a list is O(n), though.
What a strong answer covers
Draws the chain and gives the height and the n(n - 1)/2 comparison count. Says BST cost is O(h), not O(log n). Links the crash to the recursion limit and doesn't just raise it. Names balanced trees and a standard-library option.
Open in interactive practice deck →