Binary Search Trees (DSA #10)
A binary tree organizes data hierarchically but says nothing about order, so finding a value still costs \(O(n)\). A binary search tree adds one rule that turns the tree into a searchable structure: every node’s left subtree holds smaller values and its right subtree holds larger ones. That rule makes each comparison discard an entire subtree, giving \(O(\log n)\) search on a balanced tree — the tree version of binary search.
This chapter covers the BST invariant, search, insert, delete, the inorder-sorted property, validation, and the operations that reveal whether you really understand the structure.
The BST invariant
For every node:
\[ \text{all values in left subtree} < \text{node.val} < \text{all values in right subtree} \]
It is not enough that a node’s immediate children satisfy the rule — the entire subtree must. That distinction is the source of the most common BST bug (Section “Validating a BST”).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.68cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!28] (r) at (0,0) {8};
\node[n, fill=blue!12] (l) at (-1.9,-1.1) {3};
\node[n, fill=blue!12] (rr) at (1.9,-1.1) {10};
\node[n, fill=green!16] (ll) at (-2.9,-2.2) {1};
\node[n, fill=green!16] (lr) at (-0.9,-2.2) {6};
\node[n, fill=green!16] (rl) at (1.0,-2.2) {9};
\node[n, fill=green!16] (rrr) at (2.8,-2.2) {14};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
\draw[a] (rr) -- (rl); \draw[a] (rr) -- (rrr);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.7) {inorder = 1 3 6 8 9 10 14: sorted};
\end{tikzpicture}
The payoff: an inorder traversal of a BST is sorted. This one fact solves many problems — k-th smallest, validation, and range queries all fall out of it.
Search
Walk down, choosing a side at each node:
def search(node, target):
while node:
if target == node.val:
return node
node = node.left if target < node.val else node.right
return None
Each step halves the height, so search is \(O(h)\), where \(h\) is the height: \(O(\log n)\) balanced, \(O(n)\) degenerate. The same loop is the basis of floor, ceil, and predecessor/successor.
Insert
Search for the position and attach a new leaf. No restructuring is needed as long as the tree stays reasonably balanced.
def insert(node, val):
if not node:
return TreeNode(val) # found the spot
if val < node.val:
node.left = insert(node.left, val)
elif val > node.val:
node.right = insert(node.right, val)
return node
Note the recursive form returns the (possibly new) subtree root; the parent reattaches it. This “return the new subtree” pattern keeps the code short and is required for delete below.
Delete: the three cases
Deletion is where BST problems get interesting.
- Leaf — remove it.
- One child — replace the node with that child.
- Two children — replace the node’s value with its inorder successor (the smallest value in the right subtree), then delete that successor (which has at most one child).
def delete(node, val):
if not node:
return None
if val < node.val:
node.left = delete(node.left, val)
elif val > node.val:
node.right = delete(node.right, val)
else:
if not node.left:
return node.right # 0 or 1 child
if not node.right:
return node.left
succ = node.right # find inorder successor
while succ.left:
succ = succ.left
node.val = succ.val # overwrite
node.right = delete(node.right, succ.val) # remove the successor
return node
Using the inorder successor preserves the BST invariant: it is larger than everything in the left subtree and smaller than everything remaining in the right subtree.
Validating a BST
The trap: checking only left.val < node.val < right.val passes trees that violate the subtree-wide invariant. A node deep in the left subtree can be larger than an ancestor. The correct check carries down a permitted range:
def is_valid(node, low=float("-inf"), high=float("inf")):
if not node:
return True
if not (low < node.val < high):
return False
return (is_valid(node.left, low, node.val) and
is_valid(node.right, node.val, high))
At each node, the left subtree is bounded above by the node’s value, and the right subtree is bounded below by it. Alternatively, an inorder traversal must be strictly increasing — equally valid and often simpler to write.
Other BST operations
K-th smallest rides the inorder order with an early stop:
def kth_smallest(node, k):
stack = []
while node or stack:
while node:
stack.append(node); node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.val
node = node.right
Floor and ceiling are the same descent, remembering the best candidate seen so far.
def floor(node, target):
ans = None
while node:
if node.val == target:
return node.val
if node.val < target:
ans, node = node.val, node.right # best so far, try larger
else:
node = node.left
return ans
Lowest common ancestor (LCA) in a BST is decided by value: if both targets are smaller, go left; if both larger, go right; otherwise the current node is the split point.
def lca_bst(node, p, q):
while node:
if p < node.val and q < node.val:
node = node.left
elif p > node.val and q > node.val:
node = node.right
else:
return node
return None
Balance: the BST’s weakness
Insert sorted data (1, 2, 3, 4, 5) and the BST becomes a linked list: height \(n\), operations \(O(n)\).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=blue!12] (a) at (0,0) {1};
\node[n, fill=blue!12] (b) at (1.1,-0.6) {2};
\node[n, fill=blue!12] (c) at (2.2,-1.2) {3};
\node[n, fill=blue!12] (d) at (3.3,-1.8) {4};
\node[n, fill=blue!12] (e) at (4.4,-2.4) {5};
\draw[a] (a) -- (b); \draw[a] (b) -- (c); \draw[a] (c) -- (d); \draw[a] (d) -- (e);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.2,-2.9) {sorted insertions degenerate to a chain: $O(n)$};
\end{tikzpicture}
This is why self-balancing trees exist. AVL trees (Chapter 12), red-black trees, and B-trees all restore balance after each change, guaranteeing \(O(\log n)\) height. A plain BST is fine when inputs arrive in random order; it is dangerous when they arrive sorted.
Pitfalls
- Validating with only immediate children. The subtree-wide range check is required; the naive check accepts invalid trees.
- Deleting a two-child node by replacing the whole subtree. You must replace the value with the inorder successor (or predecessor) and delete that node.
- Losing the parent link on delete. The recursive “return the new subtree” pattern handles reattachment; returning raw children without reattaching breaks the tree.
- Assuming balance. A plain BST is \(O(\log n)\) only if balanced; sorted input makes it \(O(n)\).
- Ignoring duplicates. Decide whether equal keys go left, right, or are counted; be consistent.
Why is a BST’s operation cost \(O(h)\) and not guaranteed \(O(\log n)\)? How do you validate a BST correctly?
ASolution
Operations follow one root-to-leaf path, so the cost is the height \(h\); the height is \(O(\log n)\) only when balanced and \(O(n)\) when degenerate. Validate by passing down allowed (low, high) bounds so every node in a subtree respects the full ancestor constraint, or by checking that an inorder traversal is strictly increasing.
Next: Heaps and Priority Queues (DSA #11) — the structure that always hands you the extreme element next.