Lesson 138 of 296
Binary search trees
What you will learn
- The BST rule
- Searching and inserting
- Validate Binary Search Tree
- Lowest Common Ancestor in a BST
- Kth Smallest Element in a BST
- Balanced trees
On this page
The BST rule
A binary search tree (BST) is a binary tree where, for every node:
- all values in its left subtree are smaller, and
- all values in its right subtree are larger.
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7Because of this rule, searching is like binary search (Lesson 131): at each node, go left or right.
An in-order traversal of a BST gives the values in sorted order: 1 3 4 6 7 8 10 14.
Search and insert
function searchBST(root: TreeNode | null, target: number): TreeNode | null {
let node = root;
while (node !== null && node.val !== target) {
node = target < node.val ? node.left : node.right;
}
return node;
}
function insertIntoBST(root: TreeNode | null, val: number): TreeNode {
if (root === null) return new TreeNode(val);
if (val < root.val) root.left = insertIntoBST(root.left, val);
else root.right = insertIntoBST(root.right, val);
return root;
}Both are O(h), where h is the height.
Balanced vs unbalanced
- A balanced BST has height about log n: search, insert and delete are O(log n).
- If you insert sorted values (1, 2, 3, 4, ...) into a plain BST, it becomes a long chain: height n, operations O(n).
- Self-balancing trees (red-black trees, AVL trees) rebalance automatically to keep O(log n). Database indexes use a related structure, the B-tree (Part 17).
You will not usually write a balancing tree in an interview, but you should know why they exist.
Validate Binary Search Tree
Problem (LeetCode 98): is the tree a valid BST?
The trap: checking only that each node is bigger than its left child and smaller than its right child is not enough. In this tree every parent-child pair looks fine, but 3 is in the right subtree of 5, where every value must be bigger than 5:
5
/ \
4 7
/
3 3 is less than 5 but sits on 5's right sideCorrect idea: pass down the allowed range for each node. Going left, the current value becomes the new upper bound; going right, it becomes the new lower bound.
function isValidBST(root: TreeNode | null): boolean {
function check(node: TreeNode | null, low: number, high: number): boolean {
if (node === null) return true;
if (node.val <= low || node.val >= high) return false;
return check(node.left, low, node.val) && check(node.right, node.val, high);
}
return check(root, -Infinity, Infinity);
}O(n) time, O(h) space. (Alternative: do an in-order traversal and check the values are strictly increasing.)
Lowest Common Ancestor of a BST
Problem (LeetCode 235): the lowest (deepest) node that has both p and q in its subtree (a node can be an ancestor of itself).
Idea: use the BST rule. If both values are smaller than the current node, the answer is on the left; if both are bigger, on the right; otherwise the current node is where they split, so it is the answer.
function lowestCommonAncestorBST(root: TreeNode | null, p: number, q: number): TreeNode | null {
let node = root;
while (node !== null) {
if (p < node.val && q < node.val) node = node.left;
else if (p > node.val && q > node.val) node = node.right;
else return node;
}
return null;
}O(h) time, O(1) space.
For a general binary tree (LeetCode 236), there is no ordering, so you search both sides recursively: if p and q are found in different subtrees of a node, that node is the answer.
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
if (root === null || root === p || root === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left !== null && right !== null) return root;
return left ?? right;
}Kth Smallest Element in a BST
Problem (LeetCode 230): the kth smallest value (1-indexed).
In-order traversal gives sorted order, so stop at the kth visited node:
function kthSmallest(root: TreeNode | null, k: number): number {
const stack: TreeNode[] = [];
let node = root;
let count = 0;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop()!;
count++;
if (count === k) return node.val;
node = node.right;
}
throw new Error("k is larger than the number of nodes");
}O(h + k) time: it stops early.
How to say it in an interview
"In a BST every left-subtree value is smaller and every right-subtree value larger, so search and insert are O(height), which is O(log n) when balanced and O(n) when degenerate, hence self-balancing trees. In-order traversal yields sorted order, which I use for kth smallest. To validate a BST I pass down a min and max bound rather than only comparing parents with children. For the lowest common ancestor in a BST, I walk down until p and q split to different sides."
Key words
| Word | Meaning |
|---|---|
| Binary search tree | A binary tree ordered left-smaller, right-larger |
| Balanced tree | A tree with height about log n |
| Degenerate tree | A tree shaped like a chain |
| Lowest common ancestor | The deepest node with both targets below it |
| Self-balancing tree | A BST that keeps itself balanced, such as red-black |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.