BST Logic
O(h)
Use the ordering invariant: go left for smaller, right for larger; an inorder traversal yields sorted values.
0/10 solved
Recognise it
The signal
The tree is a binary search tree: kth smallest, successor, range sum, closest value, validate or recover ordering, LCA by value.
1Brute force
Treat it as a generic tree and visit every node.
2The observation
Visiting both subtrees: ordering tells you which side can contain the answer.
3Why it works
Every node in a subtree lies within the (low, high) bounds inherited from its ancestors; in-order is sorted.
Reach for it when
- +The problem says BST or you can exploit sorted-order (kth smallest, range, closest value).
- +Validate a BST, recover a BST with two swapped nodes, or search/insert by value.
- +LCA where node values let you branch by comparison.
Not 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
Intuition
A Binary Search Tree keeps an invariant at every node: everything left is smaller, everything right is larger. That ordering is the superpower — to find a value you compare and go left or right, halving the tree each step (O(height)), like binary search on an array.
Read the full intuition
The fact to internalise: an in-order traversal of a BST visits values in sorted ascending order. Left → node → right yields 1,2,3,4… So a huge class of BST problems ("kth smallest", "validate", "find two swapped nodes") reduce to "do an in-order walk and check/grab the sorted sequence."
- Kth smallest → in-order, stop at the k-th node.
- Validate → in-order values must strictly increase (or pass a (low, high) bound down each node).
- Search / insert / LCA → compare to node, branch — no full traversal needed.
LCA in a BST is clean: from the root, if both p and q are smaller go left; if both larger go right; the moment they split you're on the LCA.
Key idea
Two reflexes: (1) need sorted order or the k-th element → in-order traversal. (2) navigating by value → compare and branch, skipping half the tree.
Why it costs what it costs
Time O(h) search / O(n) traversal. comparison-branch ops cost the tree height; full in-order touches all n nodes once.
Space O(h). recursion/explicit stack equals the height — O(log n) balanced, O(n) skewed.
Practice
- Insert into a Binary Search TreeFoundationFoundationAmazon, GoogleMedium
- Range Sum of BSTApply it · Prune subtrees outside [lo, hi].Apply itMeta, AmazonEasy
- Kth Smallest Element in a BSTOne change · Inorder gives sorted order.One changeAmazon, MetaMedium
- Lowest Common Ancestor of a Binary Search TreeOne change · LCA with ordering.One changeAmazon, MetaMedium
- Validate Binary Search TreeTwists · Checking only parent-child is wrong.TwistsAmazon, MetaMedium
- Binary Search Tree IteratorBranches · Lazy inorder.BranchesMeta, AmazonMedium
- Delete Node in a BSTBranches · Structural modification.BranchesAmazon, MicrosoftMedium
- Two Sum IV - Input is a BSTCombine · Two-pointer over a BST.CombineAmazon, AdobeEasy
- Recover Binary Search TreeMastery checkMastery checkAmazon, MicrosoftMedium
- Convert Sorted Array to Binary Search TreeAmazon, AdobeEasy
Pitfalls
Classic bugs
- !Validating only parent–child (
left<node<right) — a deep node can break an ancestor bound. Pass (low, high) down. - !Validate with strict inequalities unless duplicates are allowed.
- !Kth smallest: iterative in-order, stop at k — don't build the whole list.
- !Recover BST: the swapped nodes are the out-of-order points in in-order (one dip if adjacent); track first and second.
- !Value-branching LCA only works on a BST — don't reuse it on a plain binary tree.
Go deepervariants and techniques · 3 combinations · resources
Variants and techniques
- Ordered Set / Balanced BST (TreeMap, multiset)A balanced BST supporting insert, delete, and predecessor/successor/floor/ceiling in O(log n).
- In-order = sortedTraverse left-node-right to emit/consume sorted values. Kth Smallest, Validate.
- Bounds validationPush (low, high) down; node must lie strictly inside. Validate BST.
- Compare-and-branchNavigate by value to find/insert/LCA. LCA of a BST.
- Build from sortedMiddle element = root, recurse halves for a balanced BST. Convert Sorted Array to BST.
- Detect swapsIn-order, find the misordered pair(s), swap values back. Recover BST.
Combinations
Greedy+Ordered Set / Balanced BST (TreeMap, multiset)
match customers to the highest ticket <= budget; assign k members to movies
- Greedy:
- assigns each request the best remaining resource
- Ordered Set / Balanced BST (TreeMap, multiset):
- finds the floor/ceiling resource and removes it
Manhattan <-> Chebyshev Rotation+Ordered Set / Balanced BST (TreeMap, multiset)
remove exactly one point to minimise the max Manhattan distance
- Manhattan <-> Chebyshev Rotation:
- max distance = max(range of u, range of v)
- Ordered Set / Balanced BST (TreeMap, multiset):
- multisets of u and v support removing one point and reading the new extremes
Merge Intervals+Ordered Set / Balanced BST (TreeMap, multiset)
add/remove/query ranges online (range module, count covered integers)
- Merge Intervals:
- the merge/split logic for overlapping ranges
- Ordered Set / Balanced BST (TreeMap, multiset):
- a TreeMap from start to end holds disjoint intervals with O(log n) neighbour lookup
Range ModuleCount Integers in IntervalsData Stream as Disjoint Intervals