Mental model
Binary search needs a sorted array, and keeping an array sorted while keys come and go is expensive: every insert or delete shifts up to n elements. A binary search tree stores the same ordering in links instead of positions, so a new key only needs one new link.
Each node holds a key and up to two children. The whole structure obeys one rule, the BST invariant:
For every node
x, every key inx's left subtree is smaller thanx.key, and every key in its right subtree is larger.
"Every key in the subtree" is the important part. It is not enough for the left child to be smaller. In the tree below, 60 is larger than its parent 30, which looks fine locally, but it sits in the left subtree of 50, where every key must be below 50. That tree is not a BST, and a search for 60 would go right at the root and never find it.
50
/ \
30 70
\
60 ← breaks the invariant: 60 > 50 but it is in 50's left subtree
Because of the invariant, comparing a key with one node tells you which subtree it could be in and rules out the other subtree completely, much like one comparison in binary search rules out half of the remaining range. The lab lays nodes out left to right in sorted order and one row per level, so you can see both facts at once: the row is the depth, and reading the keys left to right gives the inorder sequence, which is always sorted.
This lesson's tree stores a set of distinct integers. Inserting a key that is already there
changes nothing and returns false. Real trees often store key/value pairs and replace the value
instead, or allow duplicates by sending equal keys consistently to one side; pick one policy and
keep it, or searches and deletes will disagree with inserts.
Search
Start at the root and compare; go left on smaller, right on larger, stop on equal or when the link you need is empty.
node = root
while node != null:
if key == node.key: return true
node = key < node.key ? node.left : node.right
return false
Every iteration moves one level down, so a search makes at most h + 1 comparisons, where h is
the tree's height (the number of edges on the longest root-to-leaf path; −1 for an empty tree,
0 for a single node). When a search fails, the empty link it fell off is exactly where that key
belongs. Insert relies on this.
Minimum and maximum need no comparisons at all: the smallest key is the leftmost node, so keep following left links until there is none; the largest is the rightmost. Both are O(h).
The inorder successor of a key (the next larger key) is the minimum of its right subtree when it has one; otherwise it is the nearest ancestor whose left subtree contains the key. The predecessor is the mirror image. Delete uses the first rule.
Insert
Insert is a search that does not give up at an empty link: it attaches a new leaf there.
if root == null: root = new Node(key); return true
node = root
loop:
if key == node.key: return false # already present
child = key < node.key ? node.left : node.right
if child == null:
attach new Node(key) on that side of node; return true
node = child
Inserting never moves an existing node, which is why the invariant survives: the new key is placed where a search for it would look, and every ancestor on that path compared it correctly. The flip side is that the shape of the tree is decided entirely by the order of the inserts. Run the presets Sorted inserts: degenerate and Same keys, balanced order in the lab: the same kind of keys produce a chain of height 5 in one and a perfect tree of height 2 in the other.
Delete: three cases
Finding the node is a search. Removing it depends on how many children it has. The implementation
here is recursive: delete(node, key) returns the root of the subtree after the deletion, and each
caller stores that value back into the link it came from. That one convention handles "the deleted
node was the root" and "the deleted node was a left/right child" in the same way.
- Leaf (no children). Return
null: the parent's link simply disappears. - One child. Return that child. It takes the deleted node's place, and its whole subtree moves up one level. Nothing inside the subtree changes, so it stays ordered, and every key in it was already on the correct side of every ancestor.
- Two children. The node cannot just vanish: two subtrees would need one parent link. Instead,
find the inorder successor
s, the leftmost node of the right subtree. Copys.keyinto the node, then deletes.keyfrom the right subtree.
Why does case 3 keep the invariant? s.key is the smallest key in the right subtree, so it is
larger than everything in the left subtree (they were all smaller than the old key) and smaller than
everything else on the right. It is a valid key for that position. And deleting s afterwards is
always case 1 or 2, because the leftmost node of a subtree has no left child. The lab marks the
node being replaced and walks the successor search one link at a time: one step right, then left
until there is no left child. Between the copy and the second delete, s.key briefly exists twice;
the lab shows that too.
delete(node, key):
if node == null: return null # key not present
if key < node.key: node.left = delete(node.left, key); return node
if key > node.key: node.right = delete(node.right, key); return node
if node.left == null: return node.right # cases 1 and 2
if node.right == null: return node.left # case 2
s = node.right; while s.left != null: s = s.left # case 3: successor
node.key = s.key
node.right = delete(node.right, s.key)
return node
Using the predecessor (rightmost of the left subtree) works just as well. Always choosing the same side is asymmetric, and over long runs of random inserts and deletes it is known to skew trees away from balance; some implementations alternate. Balanced trees (module M20) remove the question by rebalancing after each change.
The preset Delete: three cases removes a leaf, a one-child node and a two-child node in that order, then validates the result.
Validating a tree
The tempting check compares each node only with its children. It passes the broken tree at the top of this lesson, because 30 < 60 locally. The correct check passes down the bounds that every ancestor imposes:
valid(node, low, high):
if node == null: return true
if (low != null and node.key <= low) or (high != null and node.key >= high): return false
return valid(node.left, low, node.key) and valid(node.right, node.key, high)
valid(root, null, null)
Going left lowers the upper bound to the current key; going right raises the lower bound. Each node
is checked once: O(n) time, O(h) stack. An equivalent check is "an inorder traversal produces a
strictly increasing sequence", which is the same fact seen from the other side. The check
operation in the lab shows the interval each node must fall into.
Cost: it is all about height
Search, insert, delete, min and max each walk one root-to-leaf path (delete may walk a second, shorter one inside the right subtree), so each costs O(h) time. The iterative search and insert use O(1) extra space; the recursive delete uses O(h) stack.
| Shape | Height h | Search / insert / delete |
|---|---|---|
| Perfectly balanced (n = 2ᵏ − 1) | ⌊log₂ n⌋ | O(log n) |
| Keys inserted in random order (expected) | O(log n); the average depth is about 1.39 log₂ n | O(log n) expected |
| Keys inserted in sorted or reverse-sorted order | n − 1 (a chain) | O(n): a linked list with extra steps |
The lower bound comes from counting: a binary tree of height h holds at most 2^(h+1) − 1 nodes, so h ≥ ⌈log₂(n + 1)⌉ − 1. The upper bound is a chain. Real input is often partly sorted (timestamps, auto-increment IDs, alphabetical imports), which is exactly the bad case, so a plain BST is rarely used directly in production. Balanced variants (AVL, red-black, B-trees) keep h = O(log n) regardless of order, at the price of rotations or splits on update.
Recursion depth follows height too. On a degenerate tree with a hundred thousand keys, the recursive delete and validation would need a hundred thousand stack frames: beyond CPython's default recursion limit (1,000) and risky in C#, Java and C++ as well. Iterative versions or a balanced tree avoid this.
Built-in ordered collections
None of the four languages exposes a plain BST, and none needs to:
| Language | Ordered set / map | Guarantee |
|---|---|---|
| C# | SortedSet<T>, SortedDictionary<TKey,TValue> |
red-black tree; O(log n) add, remove, lookup; Min, Max, GetViewBetween |
| Java | TreeSet<E>, TreeMap<K,V> |
red-black tree; O(log n) add, remove, contains; floor, ceiling, higher, lower |
| C++ | std::set, std::map |
O(log n) insert, erase, find (usually red-black); lower_bound, upper_bound |
| Python | none in the standard library | bisect on a sorted list gives O(log n) search but O(n) insertion; third-party sorted containers fill the gap |
The floor/ceiling/lower_bound family answers "the nearest key at or below / above x", the
question a hash table cannot answer and the main reason to choose an ordered structure over a hash
one.
The teaching implementation
Insert/insert and Contains/contains are iterative; Remove and the invariant check are
recursive, the same structure in all four languages so the lab can highlight matching lines.
- C# and Java compare with
CompareTo/Integer.compare, which also works for any comparable key type. Java returnsOptionalIntfrommin/max, C# returnsint?. - Python computes a three-way comparison as
(key > node.key) - (key < node.key)to mirror the other languages; idiomatic Python would just use<and==. - C++ owns nodes through
std::unique_ptr, so removing a node frees it automatically, and insert binds a reference to the emptyunique_ptrlink and assigns the new node into it.min/maxreturnstd::optional<int>.
Every language runs one shared fixture (all three delete cases, a successor deep in the right subtree, a successor with a right child, duplicates, missing keys, an empty tree, a degenerate chain, extreme keys), checks the invariant after every operation, and compares 300 random runs of 60 operations with a sorted-list model.
Common mistakes
- Checking only parent–child pairs when validating. Pass bounds down instead.
- Forgetting to store the returned subtree in the recursive delete (
delete(node.left, key)withoutnode.left = …). The node is "deleted" from a copy of the link and stays in the tree. - Deleting the successor from the wrong subtree. After copying, delete
s.keyfromnode.right, not from the root: from the root the search would stop at the node you just copied into. - Inconsistent duplicate policy, for example inserting equal keys to the right but searching or deleting as if they went left.
- Assuming O(log n). Without balancing, sorted input makes every operation linear.
Edge cases
- Empty tree: search and delete return false, min and max return nothing, validation succeeds.
- Deleting the root: works through the same "return the new subtree root" rule; with two children the root keeps its node and only its key changes.
- Deleting the only node: the tree becomes empty (case 1 at the root).
- Successor is the right child itself (it has no left child): the copy is followed by a case 1 or 2 delete one level down.
- Extreme keys (
int.MinValue,int.MaxValue): the bounds in the validator are nullable rather than sentinel values, so no key is treated as "out of range" by accident.
Worked practice
1. Insert 8, 3, 10, 1, 6, 14, 4, 7, 13 into an empty tree. What is its height, and how many comparisons does a search for 13 make?
Answer
Height 3 (8 → 3 → 6 → 4, or 8 → 10 → 14 → 13). Searching 13 compares with 8, 10, 14 and 13: four comparisons.
2. In that tree, delete 3. Which key replaces it, and what does the tree look like afterwards?
Answer
3 has two children, so take its successor: one step right to 6, then left to 4, which has no left child. Copy 4 into the node, then delete 4 from 3's old right subtree (it is a leaf). The left subtree of 8 becomes 4 with children 1 and 6, and 6 keeps its right child 7.
3. Is this tree a BST: root 10, left child 5 (whose right child is 12), right child 15?
Answer
No. 12 is in 10's left subtree, so it must be below 10. The bounds check gives 12 the interval (5, 10) and rejects it; a parent-only check would accept it because 12 > 5.
4. You must insert the keys 1…1,000 (already sorted) and then answer lookups. What goes wrong with a plain BST, and what are two fixes?
Answer
The tree becomes a chain of height 999, so each lookup costs up to 1,000 comparisons, and recursive
operations risk deep recursion. Fixes: build a balanced tree directly from the sorted list (take
the middle element as the root, recurse on each half, O(n)), or use a self-balancing tree such as
SortedSet, TreeMap or std::set. Inserting in shuffled order also gives O(log n) expected
height.
Summary
- The invariant covers whole subtrees: everything left of a node is smaller, everything right is larger. Inorder traversal therefore yields sorted order.
- Search, insert, min and max follow one path: O(h). Insert attaches a leaf where search failed.
- Delete has three cases; with two children, copy the inorder successor's key and delete the successor, which has at most one child.
- Validate with inherited bounds, not parent–child comparisons.
- h ranges from ⌊log₂ n⌋ to n − 1 depending on insertion order. Production code uses balanced
trees (
SortedSet,TreeMap,std::set) to guarantee O(log n).