Don't memorize the binary search tree — watch it grow. Every value that arrives goes left if it's smaller, right if it's larger, so the tree stays sorted without any extra work. Search then walks one path down, halving what's left at each step — O(log n). Until you feed it sorted input and it quietly collapses into a list.
insert · search · in-order · balancing
THE INVARIANT
Left subtree < node < right subtree, at every node.
SEARCH
Compare, go left or right — one path down, O(log n) when balanced.
IN-ORDER
Left, node, right → the values come out sorted.
THE CATCH
Sorted input builds a lopsided chain — O(n). Hence balancing.
Insert six values one at a time and watch the tree keep itself sorted. Press Step: each value walks down comparing — smaller goes left, larger goes right — until it finds an empty spot.
0
Nodes
—
Cost
Sorted by construction
The magic of a BST is that it never has to sort anything — the invariant does the work. Because left is always smaller and right always larger, both inserting a new value and searching for one become the same walk: start at the root, compare, and step left or right. Each step throws away a whole subtree, which is why a balanced tree answers in about log₂(n) steps.
01
Insert
Walk down comparing — smaller left, larger right — until you fall off the tree, and hang the new node there. O(log n) when balanced.
02
Search
The same walk: at each node go left or right. You either land on the value or run out of tree.
03
In-order traversal
Recurse left, visit the node, recurse right — the values come out in ascending order, for free, in O(n).
04
Balance it
Sorted input makes every node lean the same way — an O(n) chain. AVL and red-black trees rotate on insert to keep the height ~log n.
Search / Insert / Delete (balanced)
O(log n)
Worst case (degenerate)
O(n)
In-order traversal
O(n) sorted
Space
O(n)
Unlike a hash table, a BST keeps data ordered, so it answers range queries (“every value between 10 and 20”), successor/predecessor and min/max — things a hash table can't do. That ordered structure, kept balanced, is what powers database indexes (B-trees are the disk-friendly cousin) and language TreeMap/set types.
The picture: same operations, different insertion order
Six values, two orders. The left tree comes from the page’s sequence and has height 3, so any search needs at most 3 comparisons. The right tree comes from sorted input: every value is larger than all before it, so each goes right and the tree is a linked list of height 6.
Worked example, step by step
Insert 5, 3, 8, 2, 4, 7 into an empty tree. For each value, walk from the root: smaller goes left, larger goes right, and the new node hangs where the walk falls off. “Compared with” lists the nodes visited; the depth of the new node equals their count.
Insert
Compared with
Comparisons
New node’s depth level
5
(root)
0
1
3
5
1
2
8
5
1
2
2
5 → 3
2
3
4
5 → 3
2
3
7
5 → 8
2
3
The six inserts cost 8 comparisons in total, and the tree ends with height 3. The in-order traversal (left, node, right) reads 2, 3, 4, 5, 7, 8, sorted, though nothing was ever sorted. Now insert 1, 2, 3, 4, 5, 6: the comparisons per insert are 0, 1, 2, 3, 4, 5, a total of 15, and the height is 6. Scale that up and it stops being cosmetic. Inserting 1 to 1000 in ascending order costs 499,500 comparisons and builds a chain of height 1,000; the same 1000 values in one seeded random shuffle cost 11,972 comparisons and build a tree of height 25. The invariant is identical in both; only the shape differs.
Deleting from the same tree. All three cases of delete appear in this six-node tree; each starts from the original. Deleting 2 removes a leaf: unhook it from 3. Deleting 8 removes a node with one child: 7 moves up to become the right child of 5. Deleting the root 5 is the two-child case. Its in-order successor is the smallest key in its right subtree: step right to 8, then left as far as possible, which reaches 7. Copy 7 into the root and delete the old 7, a leaf. The in-order read is now 2, 3, 4, 7, 8. The successor never has a left child, so that second delete is always an easy case.
Complexity and trade-offs
Case
Time
Space
Why
BST, balanced shape
O(log n) search, insert, delete
O(n)
Height about log₂ n; each step discards a subtree.
BST, degenerate shape
O(n)
O(n)
Sorted or reverse-sorted input gives a chain. The tree is a linked list.
Self-balancing (AVL, red-black)
O(log n) guaranteed
O(n)
Rotations on insert and delete keep height logarithmic, at a constant-factor cost per update.
Hash table
O(1) average lookup
O(n)
Faster for exact lookup, but has no order: no range query, min, max or successor.
Sorted array
O(log n) search, O(n) insert
O(n)
Compact and cache-friendly, but every insertion shifts elements.
A plain BST’s expected height is logarithmic only for random insertion order; adversarial or already-sorted data defeats it, as the 1000-value chain above shows. In-order traversal is O(n) because every node is visited once, and range queries cost O(log n + k) for k results. Pointer-chasing makes trees slower per step than arrays on real hardware, which is why disk-based indexes use wide B-tree nodes instead.
Common mistakes
Checking only the parent when validating a BST
A node must lie between all its ancestors’ bounds, not just beat its parent. The tree 5 with left child 3 whose right child is 7 passes the parent check at every node, but 7 sits in the left subtree of 5 and breaks the invariant. Pass (low, high) down the recursion.
Inserting sorted data and expecting O(log n)
Feeding 1, 2, 3, … into a plain BST builds a chain. Shuffle the input first, or use a self-balancing tree.
Deleting a node with two children by removing it
Replace its value with the in-order successor (the smallest in the right subtree) or predecessor, then delete that node, which has at most one child. Splicing the node out loses a subtree.
Mishandling duplicates
The invariant “left < node < right” has no place for an equal key. Decide a rule (reject, count, or always go right) and apply it in insert, search and delete alike; mixing rules makes equal keys unfindable.
Recursing on a chain
Recursive insert or traversal on a degenerate tree recurses n deep. On a chain of 100,000 nodes that overflows the call stack in most languages; use iteration or balance the tree.
Where this shows up
Ordered maps and sets in standard libraries
Java’s TreeMap and TreeSet are red-black trees, and the usual C++ implementations of std::map and std::set use red-black trees too. Both give sorted iteration plus floor, ceiling and range operations.
Operating system kernels
The Linux kernel ships a red-black tree implementation used for ordered kernel data, including the run queue of its Completely Fair Scheduler (the default until Linux 6.6 replaced it with EEVDF), where the task with the smallest virtual runtime is the leftmost node.
Database indexes
B-trees, the disk-friendly generalisation with many keys per node, power the ordered indexes of most relational databases. The same “smaller left, larger right” rule applies inside each node.
Interview staples
“Validate Binary Search Tree” (LeetCode 98) and “Kth Smallest Element in a BST” (LeetCode 230) both rest on in-order traversal being sorted.
SOLVE IT YOURSELF
Solve it: BST in-order
This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.
YOUR TASK
Implement bst_inorder(vals): insert the values one by one into a binary search tree (smaller goes left, larger goes right), then return the in-order traversal as a list. Because of the BST ordering, that traversal comes out sorted. (Assume distinct values.)
HINTS — 4 IDEAS
A BST node holds a value plus left and right children. Insert by comparing: go left if the new value is smaller, right if larger.
Insert recursively: at an empty spot, create the node; otherwise recurse into the correct side and return the node.
In-order traversal visits left subtree → node → right subtree.
For a BST, in-order visits values in increasing order — that is why the result is sorted.
CPython · WebAssembly✓ Solved
1
1
Check yourself
1 · In a BST, where does a value smaller than the current node go?
The invariant is left < node < right, so anything smaller than a node lives in its left subtree.
2 · Which traversal prints a BST's values in sorted order?
In-order visits everything smaller (left) before the node and everything larger (right) after — ascending order.
3 · What happens if you insert already-sorted values into a plain BST?
Every value goes the same direction, so the tree becomes a linked list of height n — the reason self-balancing trees exist.
Questions
BST vs hash table — which should I use?
A hash table gives O(1) average lookup but no order. A balanced BST gives O(log n) lookup and keeps keys sorted, so it supports range queries, ordered iteration, and min/max/successor. Use a hash table for pure key lookup; a tree when order matters.
What is a self-balancing tree?
A BST that rotates nodes on insert and delete to keep its height near log n, so operations stay O(log n) no matter the input order. AVL trees keep strict balance; red-black trees keep looser balance with fewer rotations; B-trees generalize the idea for disk and databases.
How do you delete a node with two children?
Replace it with its in-order successor (the smallest value in its right subtree) or predecessor, then delete that node — which has at most one child, an easy case. This preserves the BST invariant.
Ordered, and fast — while it's balanced.
Smaller left, larger right, search in O(log n), sorted for free. Just keep it from leaning.