Learn the pattern · ~15 min
BST Logic
also called inorder = sorted, bounds propagation
In a BST everything to the left is smaller and everything to the right is bigger, so compare and go one way, and an in-order walk reads the values in sorted order.
Reach for it when you read
- +The input is a BST and the question is about order: k-th smallest, next bigger, the previous value, "is it sorted?".
- +Search, insert, delete, floor or ceiling of a value in a BST: compare and walk one path, O(h).
- +Two values in a BST and their common ancestor, or a range [lo, hi]: the BST rule tells you which side to skip.
- +Flatten or convert a BST into a sorted list in place: in-order with a running tail.
- +Two nodes were swapped, or you must check validity: in-order exposes any value that is out of order.
Not this one when
- ×A plain binary tree with no ordering rule: compare and branch means nothing; use tree DFS.
- ×You need sorted order with fast inserts but you don't have to build the tree: a set/map (a balanced BST) or a heap.
- ×Values by level or nearest to the root: tree BFS.
Learn BST Logic
First, what is a "binary search tree"?
Binary means every node has at most two children, left and right. A binary search tree (BST) adds one rule, at every node:
Everything in the left subtree is smaller than the node. Everything in the right subtree is bigger.
A root 5 with left child 2 and right child 8 is a BST; swap 2 and 8 and it isn't. The rule covers the whole subtree, not just the children. Our tree:
6
/ \
3 9
/ \ /
1 4 8
\
55 is 4's right child, so bigger than 4. It's also in 3's right subtree and 6's left subtree: 3 < 4 < 5 < 6. Every ancestor bounds it.
Move 1: compare and go one way
Search for 5: smaller goes left, bigger goes right.
| at | 5 vs node | what happens | go |
|---|---|---|---|
| 6 | smaller | everything on 6's right is bigger than 6, so 5 can't be there | left |
| 3 | bigger | 5 can't be in 3's left side | right |
| 4 | bigger | same reason | right |
| 5 | equal | found it | stop |
1, 9 and 8 were never touched. A search for 7 goes 6 → 9 → 8 → an empty left child: not there.
Move 2: in-order reads it sorted
In-order means: the left subtree, then the node, then the right subtree. On a BST that prints the values sorted. Here it is with the stack the recursion keeps: go left as far as you can, pushing every node; pop one, print it, repeat from its right child.
| step | what happens | printed | stack after (bottom → top) |
|---|---|---|---|
| 1 | from 6 go left all the way: push 6, 3, 1; pop 1 | 1 | 6, 3 |
| 2 | 1 has no right child; pop 3 | 3 | 6 |
| 3 | 3's right child is 4: push it (no left), pop it | 4 | 6 |
| 4 | 4's right child is 5: push, pop | 5 | 6 |
| 5 | 5 has no right; pop 6 | 6 | empty |
| 6 | 6's right is 9: push 9, then its left 8; pop 8 | 8 | 9 |
| 7 | pop 9; it has no right child, and the stack is empty: done | 9 | empty |
1 3 4 5 6 8 9: sorted.
The code for it
TreeNode* search(TreeNode* node, int x) {
while (node && node->val != x)
node = x < node->val ? node->left : node->right; // the other side can't hold x
return node;
}
void inorder(TreeNode* node) {
if (!node) return;
inorder(node->left); // everything smaller first
cout << node->val << ' ';
inorder(node->right); // then everything bigger
}You don't need to memorise this: search is the first table, inorder the second.
Why does in-order come out sorted? At every node, everything smaller is in its left subtree, printed in full before the node, and everything bigger is printed after.
Search costs one step per level, the tree's height: about 20 steps for 10⁶ balanced nodes, n for one long chain.
Fine, but how does this help us?
Here's a classic problem, Increasing Order Search Tree: flatten a BST into a sorted list, in place. No node keeps a left child, and each right points to the next bigger value.
By hand: take the in-order list from move 2 and point each node at the value after it.
| node | 1 | 3 | 4 | 5 | 6 | 8 | 9 |
|---|---|---|---|---|---|---|---|
next bigger, its new right |
3 | 4 | 5 | 6 | 8 | 9 | null |
The answer is 1 → 3 → 4 → 5 → 6 → 8 → 9.
The brute force
A natural plan: flatten the left subtree into a list, walk to its end, hang the root there, then flatten the right subtree and hang it on the root.
TreeNode* flattenBrute(TreeNode* root) {
if (!root) return nullptr;
TreeNode* head = flattenBrute(root->left); // the left subtree as a list
root->left = nullptr;
if (head) {
TreeNode* t = head;
while (t->right) t = t->right; // walk to the end of that list
t->right = root;
} else head = root;
root->right = flattenBrute(root->right);
return head;
}It gives 1 3 4 5 6 8 9, and it looks like one visit per node. But the while walks the whole left list every time. On a tree leaning left (n, n − 1, …, 1, each the left child of the one before), node k walks k − 2 steps: 49,985,001 for n = 10⁴, about 5 × 10⁹ for n = 10⁵. That's O(n²), not O(n). LeetCode caps this problem at 100 nodes, so it passes there; at 10⁵ nodes it takes 4 seconds (-O2): time limit exceeded.
The one thought that fixes it
Stop at node 6. The brute force has just built 1 → 3 → 4 → 5 from 6's left subtree, and now walks 1, 3, 4, 5 to find its end. But in-order visits nodes in the list's order, and it visited 5 right before 6. The end of the list is always the node visited just before.
So remember the end: keep tail, the last node appended. Each visit is one append, tail->right = node; tail = node. A dummy node in front gives node 1 a tail too.
Is rewiring mid-walk safe? A node's left subtree is done before its visit, so cutting left loses nothing, and its right is overwritten only by the next visit, after visit(node->right) has read it.
TreeNode* tail; // the last node of the list so far
void visit(TreeNode* node) {
if (!node) return;
visit(node->left);
node->left = nullptr;
tail->right = node; // append right after the previous node
tail = node;
visit(node->right);
}
TreeNode* increasingBST(TreeNode* root) {
TreeNode dummy(0); // so the first node needs no special case
tail = &dummy;
visit(root);
return dummy.right;
}Dry run
The call stack column is the recursion at the moment of each visit:
| visit | call stack (root → current) | tail before | link made |
|---|---|---|---|
| 1 | 6, 3, 1 | dummy | dummy->right = 1 |
| 3 | 6, 3 | 1 | 1->right = 3 |
| 4 | 6, 3, 4 | 3 | 3->right = 4 |
| 5 | 6, 3, 4, 5 | 4 | 4->right = 5 |
| 6 | 6 | 5 | 5->right = 6 |
| 8 | 6, 9, 8 | 6 | 6->right = 8 |
| 9 | 6, 9 | 8 | 8->right = 9 |
The list from dummy.right reads 1 3 4 5 6 8 9, the same answer as the brute force.
Why it's O(n)
Count what happens to each node: it is visited once and linked once, and nothing is walked again: O(n) time. Space is the recursion stack: O(h) for height h.
From O(n²) to O(n), by remembering the tail instead of walking to it.
K-th smallest? Count down during in-order
In-order hands you values smallest first, so the k-th to arrive is the answer. Put this at the visit, and stop the walk once it fires:
if (--k == 0) { kth = node->val; return; } // the k-th value to arriveWith k = 3 the values arrive 1, 3, 4: the answer is 4, without walking the rest.
Validate a BST? Compare with the previous one
A tree is a BST exactly when its in-order list is strictly increasing. Keep the previous node:
if (prevNode && node->val <= prevNode->val) ok = false; // must be strictly bigger
prevNode = node;Our tree passes. Now change 5 to 7. A parent-only check misses it (7 > 4, fine for a right child), but 7 sits in 6's left subtree. In-order reads 1 3 4 7 6, and 6 ≤ 7 catches it. The <= rejects equal values too.
Range sum? Prune with the rule
Sum every value in [lo, hi]. Move 1 again: a node below lo has its whole left side below too.
int rangeSum(TreeNode* node, int lo, int hi) {
if (!node) return 0;
if (node->val < lo) return rangeSum(node->right, lo, hi); // node and its left are too small
if (node->val > hi) return rangeSum(node->left, lo, hi); // node and its right are too big
return node->val + rangeSum(node->left, lo, hi) + rangeSum(node->right, lo, hi);
}For [4, 8]: 4 + 5 + 6 + 8 = 23. Node 1 is never visited: at 3, which is below 4, the walk goes only right.
Remember this
- Whenever a BST problem asks about sorted order, the k-th value, the previous or next value, or validity: in-order, carrying the previous node.
- Find, insert, a range, the split point of two values: compare and go one way, O(h).
- The rule binds every ancestor, not just the parent: validate against the in-order previous (or pass bounds down).
- Building a list during in-order: keep the tail, or it's O(n²).
Practise it on Range Sum of BST, then Validate Binary Search Tree, Lowest Common Ancestor of a BST (walk down until the two values split), Kth Smallest Element in a BST, Binary Search Tree Iterator (the stack table, paused between calls) and Recover Binary Search Tree (in-order finds the two swapped nodes).
Below, watch Kth Smallest Element in a BST run line by line.
Watch it work, line by line
Kth Smallest Element in a BST ↗, root = [5, 3, 6, 2, 4, null, null, 1], k = 3 → 3. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is it a binary search tree, and does the question care about order: the smallest, the k-th, the next bigger, a range, or the closest value?
Reach for it when
- +the input is a binary SEARCH tree
- +k-th smallest, successor, range sum
- +validate or repair ordering
- +h = log n if balanced, n if skewed
It fails when
- ×General binary tree with no orderinguse Plain tree DFS/BFS
- ×Frequent inserts/deletes or a skewed tree where you need guaranteed O(log n)use Language ordered set / balanced tree
- ×You need level order or shortest depthuse BFS
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why isn't checking
left < node < rightat every node enough to validate a BST?RevealA deep node can satisfy its parent and still break an ancestor's bound. Pass
(low, high)down from the root.2In what order does an in-order walk visit a BST?Reveal
Ascending. Right, node, left gives descending.
3What does a BST search cost, and when is that bad?Reveal
O(h). It's O(log n) when the tree is balanced and O(n) when it's skewed into a chain.
Practice ladder
- 1Range Sum of BSTprune a rangeEasy
- 2Insert into a Binary Search Treecompare and branchMedium
- 3Validate Binary Search Treevalidate with boundsMedium
- 4Lowest Common Ancestor of a Binary Search Treethe split pointMedium
- 5Kth Smallest Element in a BSTthe hookMedium
- 6Binary Search Tree Iteratora lazy in-orderMedium
- 7Delete Node in a BSTchange the treeMedium
- 8Recover Binary Search Treein-order as a detectorMedium
Finished BST Logic? Mark it done and Lessgo moves you to the next step.