A binary search tree (BST) is a binary tree with one rule: every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. That single invariant turns lookup into a series of left-or-right decisions, like Binary Search on a linked structure. Search, insert and delete all cost O(h), which is O(log n) when the tree is balanced and O(n) when it degenerates into a chain.
Think of it like
The higher-or-lower guessing game
A friend picks a number from 1 to 100 and answers each guess with "higher" or "lower". A good player guesses 50, then 25 or 75, and needs at most 7 guesses. A BST stores those questions: each node is a guess, and the answer tells you which branch to follow. But a player who guesses 1, 2, 3, … may need 100 guesses. That is a BST built from sorted input, and it is why balance matters.
The BST invariant
For every node v: all keys in v.left are less than v.key, and all keys in v.right are greater than v.key. The rule applies to whole subtrees, not just to the two children, and it holds recursively at every node.
10
/ \
5 15
/ \
6 20 6 < 15 is fine for its parent,
but 6 sits in 10's RIGHT subtree, so 6 > 10 must holdDuplicates need a policy. Either reject them (set semantics), store a count in the node (multiset), or consistently send equal keys to one side, for example left < key <= right. Mixing policies breaks search.
Search
Start at the root and compare. Equal: found. Smaller: go left. Larger: go right. Fall off the tree: the key is absent. Each comparison descends one level, so search costs O(h) comparisons and needs no recursion.
Insert
Search for the key; the null link where the search falls off the tree is exactly where the key belongs. Attach a new leaf there. New keys always become leaves, so the shape of a BST is decided entirely by the order in which keys arrive.
50
/ \
30 70
/ \ / \
20 40 60 80 a perfect tree: height 2 for 7 keys
Inserting the same keys sorted (20, 30, 40, 50, 60, 70, 80)
gives a right-leaning chain of height 6.Delete: the three cases
Deletion first searches for the node, then handles it according to how many children it has. The first two cases are simple pointer surgery; the third reduces to one of the first two.
- 1
Case 1: leaf
No children. Replace the parent's link to it with null.
- 2
Case 2: one child
Splice it out: the parent links directly to the node's only child. The child's whole subtree moves up one level, and ordering is preserved because it was already on the correct side of the parent.
- 3
Case 3: two children
Find the in-order successor, the minimum of the right subtree (go right once, then left until you cannot). Copy its key into the node, then delete the successor from the right subtree.
- 4
Why case 3 is safe
The successor is the smallest key larger than the deleted one, so it fits perfectly in its place. It has no left child (otherwise that child would be smaller), so removing it is always case 1 or case 2.
| Operation | Case | Tree after (pre-order with children) |
|---|---|---|
| Start | 50 (30 (20, 40), 70 (60, 80)) | |
| Delete 20 | Leaf | 50 (30 (-, 40), 70 (60, 80)) |
| Delete 30 | One child: 40 moves up | 50 (40, 70 (60, 80)) |
| Delete 50 | Two children: successor 60 replaces it | 60 (40, 70 (-, 80)) |
Successor and predecessor
- Successor with a right subtree: the minimum of the right subtree.
- Successor without a right subtree: the lowest ancestor whose left subtree contains the node. Walking from the root, remember the last node where you turned left.
- Predecessor is the mirror image: maximum of the left subtree, or the last ancestor where you turned right.
- Both take O(h). Trees with parent pointers can walk upward instead of restarting from the root.
Ordered queries for free
| Query | How | Cost |
|---|---|---|
| Minimum / maximum | Follow left (or right) links until null | O(h) |
| Floor(x): largest key <= x | When key <= x, record it and go right; otherwise go left | O(h) |
| Ceiling(x): smallest key >= x | When key >= x, record it and go left; otherwise go right | O(h) |
| k-th smallest | In-order walk that stops after k nodes | O(h + k) |
| k-th smallest, rank | Store subtree sizes; choose left, self or right by comparing k with size(left) | O(h) |
| Range [lo, hi] | In-order walk that skips subtrees entirely outside the range | O(h + output) |
Validating a BST
Pass an open interval (low, high) down the recursion. The root may hold anything. Going left tightens the upper bound to the current key; going right tightens the lower bound. A node is valid if low < key < high and both subtrees are valid. An equivalent approach is an in-order walk that checks each key is strictly greater than the previous one.
Lowest common ancestor in a BST
In a general binary tree, finding the lowest common ancestor (LCA) of two nodes requires exploring both subtrees. In a BST the keys tell you where to go: if both targets are smaller than the current key, the LCA is on the left; if both are larger, it is on the right; otherwise the targets split here (or one of them is this node), so this node is the LCA. One downward walk, O(h) time and O(1) space.
Why height is everything
Every operation above is O(h). If keys arrive in random order, the expected height is O(log n) and the average node depth is about 2 ln n ≈ 1.39 log₂ n. But insert keys in sorted order and every new key becomes the right child of the previous one: the tree is a linked list with height n − 1, and every operation degrades to O(n).
Best height, n = 10⁶
19
⌊log₂ n⌋, perfectly balanced
Avg depth, random order
≈ 25
≈ 2 ln n − 2.85
Height, sorted input
999,999
a chain of n nodes
Random insertion order
- Expected height O(log n)
- Operations are fast on average
- No guarantee: an adversary or sorted data breaks it
Sorted or nearly sorted input
- Each key becomes the right child of the last
- Height n − 1, every operation O(n)
- Recursive code can overflow the stack
| Structure | Search | Insert / delete | Ordered queries |
|---|---|---|---|
| Sorted array | O(log n) | O(n) | Yes, by index |
| Hash table | O(1) average | O(1) average | No |
| Unbalanced BST | O(h), up to O(n) | O(h), up to O(n) | Yes |
| Balanced BST | O(log n) | O(log n) | Yes |
TreeMap, C++ std::map) over a hash table when you need floor, ceiling, range scans, min/max or sorted iteration.Complexity
| Operation | Average | Worst | Notes |
|---|---|---|---|
| Search | O(log n) | O(n) | Worst case on sorted insertion order |
| Insert | O(log n) | O(n) | New key always becomes a leaf |
| Delete | O(log n) | O(n) | Two-child case adds a walk to the successor |
| Min, max, floor, ceiling, successor | O(log n) | O(n) | One root-to-leaf walk |
| k-th smallest (in-order walk) | O(log n + k) | O(n) | O(h) with stored subtree sizes |
| In-order traversal | O(n) | O(n) | Produces sorted output |
| Space | O(n) | O(n) | Plus O(h) stack for recursive code |
"Average" assumes keys arrive in random order. Self-balancing BSTs turn these average bounds into worst-case guarantees.
Implementation
Iterative search, recursive insert and delete. Delete handles all three cases, using the in-order successor for nodes with two children. Duplicates are ignored.
from typing import Optional
class Node:
def __init__(self, key: int):
self.key = key
self.left: Optional["Node"] = None
self.right: Optional["Node"] = None
class BST:
def __init__(self) -> None:
self.root: Optional[Node] = None
def search(self, key: int) -> bool:
node = self.root
while node:
if key == node.key:
return True
node = node.left if key < node.key else node.right
return False
def insert(self, key: int) -> None:
self.root = self._insert(self.root, key)
def _insert(self, node: Optional[Node], key: int) -> Node:
if node is None:
return Node(key) # fell off the tree: new leaf
if key < node.key:
node.left = self._insert(node.left, key)
elif key > node.key:
node.right = self._insert(node.right, key)
return node # equal keys are ignored
def delete(self, key: int) -> None:
self.root = self._delete(self.root, key)
def _delete(self, node: Optional[Node], key: int) -> Optional[Node]:
if node is None:
return None # key not present
if key < node.key:
node.left = self._delete(node.left, key)
elif key > node.key:
node.right = self._delete(node.right, key)
else:
if node.left is None: # cases 1 and 2
return node.right
if node.right is None:
return node.left
succ = node.right # case 3: two children
while succ.left:
succ = succ.left # successor = min of right subtree
node.key = succ.key
node.right = self._delete(node.right, succ.key)
return node
def inorder(self) -> list[int]:
out: list[int] = []
def walk(n: Optional[Node]) -> None:
if n:
walk(n.left)
out.append(n.key)
walk(n.right)
walk(self.root)
return out
tree = BST()
for k in [50, 30, 70, 20, 40, 60, 80]:
tree.insert(k)
tree.delete(50)
print(tree.inorder(), tree.root.key) # [20, 30, 40, 60, 70, 80] 60Key takeaways
- The invariant is about whole subtrees: everything on the left is smaller and everything on the right is larger, at every node.
- Search, insert, delete, min/max, floor/ceiling and successor are all one root-to-leaf walk: O(h).
- Delete has three cases; with two children, copy the in-order successor (or predecessor) and delete it from its subtree instead.
- In-order traversal yields sorted keys, which gives validation, k-th smallest and range queries almost for free.
- h is O(log n) for random insertion order but n − 1 for sorted input, so production code uses self-balancing trees.
Common pitfalls
- Validating by comparing each node only with its direct children, which misses violations deeper in the tree.
- Using
intsentinels such asInteger.MIN_VALUEas validation bounds, which fails when a real key equals the sentinel. Use wider types or nullable bounds. - Forgetting to reassign the returned subtree (
node.left = insert(node.left, key)), so new nodes are never attached. - In the two-children delete case, deleting the successor from the whole tree instead of from the right subtree, or forgetting that the successor may still have a right child.
- Assuming O(log n) without balancing: feeding sorted data into a plain BST silently produces O(n) operations.
Interview tips
- State the duplicate policy and whether the tree is balanced before analyzing complexity; quote O(h) and then explain both extremes.
- For validation, explain why local checks fail using a small counterexample, then give the bounds method or the in-order method.
- Lean on the invariant to prune: LCA, floor, ceiling, closest value and range sum should never visit both subtrees of a node.
- If asked to make operations like k-th smallest O(h), propose augmenting each node with its subtree size and keeping it updated on insert and delete.
Real-world applications
- Ordered maps and sets: Java
TreeMap/TreeSetand C++std::map/std::set(balanced BSTs underneath). - Scheduling and event simulation where you repeatedly need the next event after a given time (ceiling queries).
- Interval and order-statistic trees, which augment BST nodes with extra summary data.
- Symbol tables in compilers and interpreters that need sorted iteration.
- Database indexes use the same ordering idea in a wider, disk-friendly form: B-Trees & B+ Trees.
Practice problems
Test yourself
You insert 1, 2, 3, 4, 5 in that order into an empty BST. What is the height of the result (counting edges)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.