Binary Search Trees
Ordered binary trees with O(h) search, insert and delete — and why the height h is everything.
A binary search tree (BST) is a binary tree with one invariant, applied at every node:
All keys in the left subtree are smaller than the node's key, and all keys in the right subtree are larger.
That single rule turns the tree into a decision structure: at each node you go left or right, discarding a whole subtree — binary search on a structure you can insert into cheaply.
Operations
Every operation walks one root-to-leaf path, so it costs O(h) where h is the height.
| Operation | Balanced (h ≈ log n) | Degenerate (h ≈ n) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Min / max | O(log n) | O(n) |
| Sorted iteration | O(n) | O(n) |
Delete: three cases
- Leaf — just remove it.
- One child — splice: replace the node with its child.
- Two children — copy in the in-order successor (minimum of the right subtree), then delete that successor from the right subtree (it has at most one child).
class BST {
TreeNode root;
boolean contains(int key) {
TreeNode n = root;
while (n != null) {
if (key == n.val) return true;
n = key < n.val ? n.left : n.right;
}
return false;
}
void insert(int key) { root = insert(root, key); }
private TreeNode insert(TreeNode n, int key) {
if (n == null) return new TreeNode(key);
if (key < n.val) n.left = insert(n.left, key);
else if (key > n.val) n.right = insert(n.right, key);
return n; // duplicates ignored
}
void delete(int key) { root = delete(root, key); }
private TreeNode delete(TreeNode n, int key) {
if (n == null) return null;
if (key < n.val) n.left = delete(n.left, key);
else if (key > n.val) n.right = delete(n.right, key);
else {
if (n.left == null) return n.right; // 0 or 1 child
if (n.right == null) return n.left;
TreeNode s = n.right; // 2 children: successor
while (s.left != null) s = s.left;
n.val = s.val;
n.right = delete(n.right, s.val);
}
return n;
}
}class BST:
def __init__(self):
self.root = None
def contains(self, key) -> bool:
n = self.root
while n:
if key == n.val:
return True
n = n.left if key < n.val else n.right
return False
def insert(self, key):
def ins(n):
if not n: return TreeNode(key)
if key < n.val: n.left = ins(n.left)
elif key > n.val: n.right = ins(n.right)
return n
self.root = ins(self.root)
def delete(self, key):
def dele(n, key):
if not n: return None
if key < n.val: n.left = dele(n.left, key)
elif key > n.val: n.right = dele(n.right, key)
else:
if not n.left: return n.right
if not n.right: return n.left
s = n.right
while s.left: s = s.left
n.val = s.val
n.right = dele(n.right, s.val)
return n
self.root = dele(self.root, key)class BST {
root: TreeNode | null = null;
contains(key: number): boolean {
let n = this.root;
while (n) {
if (key === n.val) return true;
n = key < n.val ? n.left : n.right;
}
return false;
}
insert(key: number) {
const ins = (n: TreeNode | null): TreeNode => {
if (!n) return new TreeNode(key);
if (key < n.val) n.left = ins(n.left);
else if (key > n.val) n.right = ins(n.right);
return n;
};
this.root = ins(this.root);
}
delete(key: number) {
const del = (n: TreeNode | null, k: number): TreeNode | null => {
if (!n) return null;
if (k < n.val) n.left = del(n.left, k);
else if (k > n.val) n.right = del(n.right, k);
else {
if (!n.left) return n.right;
if (!n.right) return n.left;
let s = n.right;
while (s.left) s = s.left;
n.val = s.val;
n.right = del(n.right, s.val);
}
return n;
};
this.root = del(this.root, key);
}
}Try it
Insert, search and delete — then press Sorted insert to watch a BST degenerate into a list.
The height problem
Insert 1, 2, 3, 4, 5 in order and every node becomes a right child: height n − 1, every operation O(n). The fix is a self-balancing BST that restructures itself to keep h = O(log n) — see Balanced trees. Library ordered maps (TreeMap, C++ std::map) are all balanced.
Useful BST queries
- Floor / ceiling — largest key ≤ x / smallest key ≥ x: walk down, remembering the best candidate.
- Successor — if the node has a right subtree, its minimum; otherwise the nearest ancestor whose left subtree contains the node.
- k-th smallest — in-order traversal, stop at k (or store subtree sizes for O(h)).
- Range query [lo, hi] — in-order traversal that prunes subtrees outside the range: O(h + k).
boolean isValidBST(TreeNode root) { return valid(root, Long.MIN_VALUE, Long.MAX_VALUE); }
boolean valid(TreeNode n, long lo, long hi) {
if (n == null) return true;
if (n.val <= lo || n.val >= hi) return false;
return valid(n.left, lo, n.val) && valid(n.right, n.val, hi);
}def is_valid_bst(root) -> bool:
def valid(n, lo, hi):
if not n: return True
if not (lo < n.val < hi): return False
return valid(n.left, lo, n.val) and valid(n.right, n.val, hi)
return valid(root, float("-inf"), float("inf"))function isValidBST(root: TreeNode | null): boolean {
const valid = (n: TreeNode | null, lo: number, hi: number): boolean =>
!n || (n.val > lo && n.val < hi && valid(n.left, lo, n.val) && valid(n.right, n.val, hi));
return valid(root, -Infinity, Infinity);
}- BST invariant: left < node < right, for every node.
- Search/insert/delete are O(h); in-order traversal yields sorted keys.
- Without balancing, sorted inputs give h = n. Production code uses balanced trees.
QFind the k-th smallest element in a BST.medium
Iterative in-order traversal; decrement k on each visit and return when it hits 0. O(h + k). If asked repeatedly with updates, store subtree sizes in each node and descend in O(h).
QConvert a sorted array to a height-balanced BST.easy
Pick the middle element as the root, recursively build the left half and the right half as its subtrees. O(n).
QLCA in a BST?easy
Walk from the root: if both values are smaller, go left; if both are larger, go right; otherwise the current node is the split point and the LCA. O(h).