Binary Search Trees: Searching, Minimum and Maximum
A binary search tree (BST) is a binary tree whose keys are arranged so that a search can discard a whole subtree at every step, just like binary search discards half of a sorted array. Unlike a sorted array, a BST also supports insertion and deletion without shifting anything. Every operation of this section costs , where is the height of the tree, so everything depends on keeping small. The red-black trees later in the course guarantee ; this section studies the plain structure first.
The BST lesson in the DSA course introduces the structure by example. Here the operations come with invariants and cost bounds.
The binary-search-tree property
Each node has a key and pointers , and (Representing Rooted Trees). The tree satisfies the BST property:
For every node : every key in the left subtree of is at most , and every key in the right subtree is at least .
The property is about whole subtrees, not just children. A tree in which every left child is smaller than its parent and every right child larger can still violate it: a large key deep in a left subtree, below a right child, is a classic bug. This course stores distinct keys unless said otherwise.
Inorder walk: the keys in sorted order
An inorder walk prints the left subtree, then the root, then the right subtree. By the BST property everything printed before the root is at most the root's key and everything after is at least it, so by induction on the size of the tree the walk prints all keys in sorted order.
The walk takes time on an -node tree. Proof: Let be its time. If the left subtree has nodes, for a constant , with . Substituting checks the recurrence: . And because every node is visited.
TREE-SEARCH(x, k) TREE-MINIMUM(x)
1 while x != NIL and k != x.key 1 while x.left != NIL
2 if k < x.key 2 x = x.left
3 x = x.left 3 return x
4 else x = x.right
5 return xSearching
TREE-SEARCH starts at the root and compares: if is smaller than the node's key, can only be in the left subtree; if larger, only in the right. The nodes it visits form a path down from the root, so it takes time. The iterative form above is preferred to recursion: it is just as short and uses no stack.
Minimum and maximum follow the same idea without comparisons: the minimum is reached by going left until there is no left child (anything smaller would have to be in a left subtree), the maximum by going right. Both are .
The program builds the tree of the animation, prints the search paths for 32 and 60 as the animation shows them, the minimum and maximum, and the inorder walk. The tree is built with the insertion procedure from Insertion and Deletion with Transplant.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key):
self.key, self.left, self.right, self.parent = key, None, None, None
def insert(root, key): # returns the (possibly new) root
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
def search(x, k, trace):
while x is not None and k != x.key:
go = "left" if k < x.key else "right"
trace.append(f"{'smaller' if k < x.key else 'larger'} than {x.key}, go {go}")
x = x.left if k < x.key else x.right
trace.append("found" if x else "reached an empty spot: not in the tree")
return x
def minimum(x):
while x.left is not None: x = x.left
return x
def maximum(x):
while x.right is not None: x = x.right
return x
def inorder(x, out):
if x is not None:
inorder(x.left, out); out.append(x.key); inorder(x.right, out)
return out
root = None
for k in [41, 20, 65, 11, 29, 50, 91, 32, 72, 99, 26]:
root = insert(root, k)
for k in [32, 60]:
trace = []
search(root, k, trace)
print(f"search {k}: " + "; ".join(trace))
print("minimum", minimum(root).key, "| maximum", maximum(root).key)
print("inorder:", inorder(root, []))search 32: smaller than 41, go left; larger than 20, go right; larger than 29, go right; found
search 60: larger than 41, go right; smaller than 65, go left; larger than 50, go right; reached an empty spot: not in the tree
minimum 11 | maximum 99
inorder: [11, 20, 26, 29, 32, 41, 50, 65, 72, 91, 99]
Checking the BST property
A correct check passes bounds down the tree: every key in the left subtree of must lie between the lower bound inherited from above and . Comparing each node only with its children misses violations. The program builds a tree that the naive check accepts and the bounded check rejects, and then confirms on 500 random trees that the inorder walk is sorted and that every search for a stored key succeeds within comparisons.
import random
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right, self.parent = key, left, right, None
def naive_ok(x):
if x is None: return True
if x.left and x.left.key > x.key: return False
if x.right and x.right.key < x.key: return False
return naive_ok(x.left) and naive_ok(x.right)
def is_bst(x, lo=float("-inf"), hi=float("inf")):
if x is None: return True
return lo <= x.key <= hi and is_bst(x.left, lo, x.key) and is_bst(x.right, x.key, hi)
bad = Node(30, Node(20, None, Node(35)), Node(40)) # 35 sits in 30's left subtree
print("naive check:", naive_ok(bad), "| bounded check:", is_bst(bad))
def insert(root, key):
z, y, x = Node(key), None, root
while x is not None:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is None: return z
if key < y.key: y.left = z
else: y.right = z
return root
def height(x):
return -1 if x is None else 1 + max(height(x.left), height(x.right))
def comparisons(x, k):
c = 0
while x is not None:
c += 1
if k == x.key: return c
x = x.left if k < x.key else x.right
return c
def walk(x, out):
if x: walk(x.left, out); out.append(x.key); walk(x.right, out)
return out
rng = random.Random(12)
worst_ratio = 0
for trial in range(500):
keys = rng.sample(range(1000), rng.randint(1, 60))
root = None
for k in keys:
root = insert(root, k)
assert is_bst(root) and walk(root, []) == sorted(keys)
h = height(root)
assert all(comparisons(root, k) <= h + 1 for k in keys)
print("500 random trees: BST property holds, inorder is sorted, every search uses at most h + 1 comparisons")naive check: True | bounded check: False
500 random trees: BST property holds, inorder is sorted, every search uses at most h + 1 comparisons
In C++
The C++ tree keeps its nodes in a std::vector and uses the index for NIL, so there is no manual memory management. Search, minimum, maximum and the inorder walk are direct translations.
#include <cstdio>
#include <vector>
struct BST {
struct Node { int key, left = -1, right = -1, parent = -1; };
std::vector<Node> t;
int root = -1;
void insert(int key) {
int y = -1, x = root;
while (x != -1) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
int z = static_cast<int>(t.size());
t.push_back({key, -1, -1, y});
if (y == -1) root = z;
else if (key < t[y].key) t[y].left = z;
else t[y].right = z;
}
int search(int k, int& steps) const {
int x = root;
steps = 0;
while (x != -1 && k != t[x].key) { ++steps; x = k < t[x].key ? t[x].left : t[x].right; }
return x;
}
int minimum(int x) const { while (t[x].left != -1) x = t[x].left; return x; }
int maximum(int x) const { while (t[x].right != -1) x = t[x].right; return x; }
void inorder(int x, std::vector<int>& out) const {
if (x == -1) return;
inorder(t[x].left, out); out.push_back(t[x].key); inorder(t[x].right, out);
}
};
int main() {
BST b;
for (int k : {41, 20, 65, 11, 29, 50, 91, 32, 72, 99, 26}) b.insert(k);
for (int k : {32, 60}) {
int steps;
int x = b.search(k, steps);
std::printf("search %d: %s after %d step(s) down\n", k, x == -1 ? "not found" : "found", steps);
}
std::printf("minimum %d, maximum %d\ninorder:", b.t[b.minimum(b.root)].key, b.t[b.maximum(b.root)].key);
std::vector<int> keys;
b.inorder(b.root, keys);
for (int k : keys) std::printf(" %d", k);
std::printf("\n");
}search 32: found after 3 step(s) down
search 60: not found after 3 step(s) down
minimum 11, maximum 99
inorder: 11 20 26 29 32 41 50 65 72 91 99
Test yourself
In a BST with distinct keys, where is the minimum?
- at the root
- at the leftmost node: follow left pointers from the root until there is no left child
- at any leaf
- at the deepest node
Which tree violates the BST property even though every left child is smaller and every right child larger than its parent?
- root 30, left child 20, right child 40
- root 30, left child 20 with right child 35, right child 40
- root 30, left child 20 with left child 10, right child 40
- root 30 alone
What is the worst-case cost of TREE-SEARCH on a BST of height with nodes?
- always
- , which can be for a degenerate tree