BST Practice Problems
How to Use This Problem List
BST problems require a different thinking mode than general binary tree problems. The BST property — left < root < right — is the key tool. Before writing any code, ask:
THINKING MODE for BST problems:
✓ Can I use the BST property to eliminate half the tree at each step?
→ O(h) solution exists (search, floor, ceil, LCA)
✓ Does the answer need sorted order?
→ Inorder traversal gives sorted sequence
✓ Does the answer need reverse sorted order?
→ Reverse inorder (Right → Root → Left)
✓ Do I need to count or accumulate across all nodes?
→ Full traversal O(n) — but can pruning reduce it?
✓ Is the structure of the tree the answer?
→ Construction / transformation problem
If BST property eliminates subtrees: O(h).
If you must visit every node: O(n).
The difference between O(log n) and O(n) is whether you exploit the BST property.
Pattern 1: BST Property Traversal — O(h) Operations
Use the BST ordering rule to navigate directly to the answer without visiting all nodes. Each step eliminates an entire subtree.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Search in BST | Easy | "find target value in BST" | Go left if target < node, right if target > node |
| Closest Value to Target | Easy | "closest value to k in BST" | Track closest seen; BST property guides direction |
| Floor in BST | Medium | "largest value ≤ k" | Record node when k > node.val, keep going right |
| Ceiling in BST | Medium | "smallest value ≥ k" | Record node when k < node.val, keep going left |
| Insert into BST | Easy | "insert value maintaining BST property" | Search for null position; insert as leaf |
| Delete from BST | Medium | "delete node from BST" | Leaf: remove; one child: replace; two children: replace with inorder successor |
| LCA of BST | Easy | "lowest common ancestor of BST" | Both < node → go left; both > node → go right; else current = LCA |
| Two Sum IV (BST) | Easy | "two nodes summing to target in BST" | HashSet + inorder; or use iterator from both ends |
Complexity target: O(h) time, O(1) or O(h) space.
Recognition signal: "find value", "search", "insert", "delete", "closest", "floor", "ceiling", "LCA in BST". Any problem where the BST ordering property can guide your path — you don't need to visit all nodes.
Pattern 2: Inorder Traversal — Sorted Output
Inorder traversal produces nodes in ascending order. These problems exploit that sorted property.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Kth Smallest Element in BST | Medium | "kth smallest in BST" | Inorder traversal, stop at k-th node |
| Validate BST | Medium | "is this a valid binary search tree" | Inorder + check prev < curr; or range [min, max] traversal |
| Convert BST to Sorted Array | Easy | "BST to sorted list/array" | Collect inorder traversal into array |
| Inorder Successor in BST | Medium | "next larger element of node p" | If right subtree exists: leftmost of right; else deepest ancestor where went left |
| Inorder Predecessor in BST | Medium | "next smaller element of node p" | If left subtree exists: rightmost of left; else deepest ancestor where went right |
| BST Iterator | Medium | "iterator yielding elements in ascending order" | Lazy stack: push left spine; next() pops and pushes right's left spine |
| Merge Two BSTs (sorted order) | Medium | "output sorted union of two BSTs" | Inorder both → two sorted arrays → merge sort step |
| Convert BST to Doubly Linked List | Medium | "BST to sorted doubly linked list in-place" | Inorder: thread nodes by adjusting left/right pointers |
Complexity target: O(n) time for full traversal, O(k) to stop at k-th element.
Recognition signal: "kth smallest", "sorted order", "validate", "successor", "predecessor", "iterator", "merge". The answer requires the BST's elements in sorted order or needs to compare adjacent values in sorted order.
Pattern 3: Reverse Inorder — Descending Order
Traverse Right → Root → Left to visit nodes in descending order. Used for kth largest and problems that accumulate from larger to smaller values.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Kth Largest Element in BST | Medium | "kth largest in BST" | Reverse inorder, stop at k-th node |
| Convert BST to Greater Sum Tree | Medium | "replace each node with sum of all greater values" | Reverse inorder + running cumulative sum |
| Sum of BST Values Greater Than k | Easy | "sum of all values > k in BST" | Reverse inorder, stop accumulating when node.val ≤ k |
| Decreasing Key Traversal | Easy | "traverse BST in non-increasing order" | Reverse inorder directly |
| Convert BST to Min Heap | Hard | "restructure BST into min-heap" | Collect inorder sorted array, build heap |
| BST to Max Heap | Hard | "convert BST to max heap" | Collect reverse inorder, assign to level-order positions |
Complexity target: O(n) or O(k) if stopping early.
Recognition signal: "kth largest", "greater than k", "descending order", "sum of nodes greater than", "max". The answer processes nodes from largest to smallest.
Pattern 4: Range Queries
Find, count, or sum elements within a value range [lo, hi]. The BST property allows pruning: skip entire subtrees known to be outside the range.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Range Sum of BST | Easy | "sum of values in [lo, hi]" | Skip left if node.val ≤ lo; skip right if node.val ≥ hi |
| Count Nodes in Range | Easy | "count values in [lo, hi]" | Same pruning as range sum; count instead of sum |
| Find Mode(s) in BST | Easy | "most frequent values in BST" | Inorder gives sorted sequence; count consecutive equal runs |
| Find All Duplicates in BST | Easy | "nodes with duplicate values" | Inorder: equal consecutive values are duplicates |
| Trim BST to Range [lo, hi] | Medium | "remove all nodes outside [lo, hi]" | Recurse: if node < lo return trimmed right; if node > hi return trimmed left |
| Delete Nodes and Return Forest | Medium | "delete nodes, return remaining trees" | Postorder: delete target, split into forest |
| Nodes in Range [lo, hi] | Easy | "collect all values in range" | Inorder with range pruning; collect matching nodes |
Complexity target: O(k + h) where k = number of values in range, h = tree height.
Recognition signal: "range [lo, hi]", "between lo and hi", "sum in range", "count in range", "trim", "within bounds". The problem restricts to a value interval.
Pattern 5: BST Construction and Transformation
Build a BST from given data or restructure an existing BST. Often involves exploiting sorted order or the BST property to avoid O(n²) naive approaches.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Convert Sorted Array to BST | Easy | "sorted array → balanced BST" | Mid as root; recurse on left and right halves |
| Convert Sorted List to BST | Medium | "sorted linked list → balanced BST" | Find mid (slow/fast pointer); recurse — O(n log n) |
| Recover BST (two nodes swapped) | Medium | "fix BST with exactly two nodes swapped" | Inorder: find two violations; swap the offending values |
| Balance a BST | Medium | "convert unbalanced BST to balanced" | Inorder to sorted array; build balanced BST from array |
| Serialize and Deserialize BST | Medium | "encode BST to string and rebuild" | Preorder serialize (no null needed); BST property for deserialize |
| Merge Two BSTs | Hard | "merge two BSTs into one BST" | Inorder both → merge sorted arrays → build from sorted |
| Build BST from Preorder Traversal | Medium | "construct BST from preorder array" | First element is root; partition by value into left/right ranges |
| Unique BSTs (Catalan number) | Medium | "how many structurally unique BSTs with n nodes" | DP: G(n) = Σ G(i-1) × G(n-i) for i in 1..n |
| Generate All Unique BSTs | Hard | "enumerate all structurally distinct BSTs" | Recursion: for each root, generate all left/right combinations |
Complexity target: O(n) or O(n log n) depending on approach.
Recognition signal: "construct BST", "convert to BST", "balanced BST", "recover", "serialize", "how many unique BSTs". The problem creates or restructures a BST.
Pattern 6: Multi-BST and Advanced
Problems involving multiple BSTs, auxiliary data structures, or combining BST properties with other techniques.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| All Nodes at Distance K from Target | Hard | "nodes exactly k edges from target (in any direction)" | BFS from target using parent pointers to go upward |
| Largest BST Subtree | Hard | "largest subtree that is a valid BST" | Postorder: each node returns (isBST, min, max, size); propagate upward |
| Two Nodes with Given Sum in BST | Easy | "two nodes summing to k" | HashSet + inorder; or two iterators from both ends |
| Count BST Nodes in Range | Medium | "count nodes in range [lo, hi] given node count is known" | BST property traversal with range checks |
| Pairs with Difference k in BST | Medium | "find all pairs with value difference = k" | Inorder → sorted array → two pointer |
| Median of BST | Medium | "find median value" | Inorder traversal, find middle element; or augmented BST with size |
Complexity target: O(n) for single-pass, O(h) for property-based navigation.
Recognition signal: "distance k from node", "in any direction", "largest BST subtree", "pairs", "count with property". These combine BST with graph-like traversal or additional data structures.
Recommended Study Order
Week 1 — BST Fundamentals Pattern 1 (Property): Search, Insert, Delete, LCA of BST, Closest Value Pattern 2 (Inorder): Validate BST, Kth Smallest, Inorder Successor Week 2 — Traversal Mastery Pattern 3 (Reverse): Kth Largest, Greater Sum Tree Pattern 4 (Range): Range Sum of BST, Trim BST Pattern 2 (Iterator): BST Iterator Week 3 — Construction Pattern 5 (Build): Sorted Array to BST, Recover BST, Serialize BST Pattern 5 (Advanced): Build from Preorder, Balance a BST Week 4 — Hard and Multi-BST Pattern 6 (Multi): All Nodes at Distance K, Largest BST Subtree Pattern 5 (Hard): Merge Two BSTs, Generate All Unique BSTs Mixed review of all patterns
Problem-Solving Checklist for BST Problems
1. CAN THE BST PROPERTY ELIMINATE SUBTREES? □ At each node, can you decide left or right based on target vs node.val? → YES: O(h) solution exists — implement as while loop traversal → NO: full O(n) traversal needed 2. WHAT TRAVERSAL ORDER GIVES THE ANSWER? □ Ascending order needed → inorder (L → Root → R) □ Descending order needed → reverse inorder (R → Root → L) □ Level-based needed → BFS with queue □ Subtree info before parent → postorder 3. FOR VALIDATION PROBLEMS: □ Never check only parent-child pairs □ Pass [min, max] range downward: left gets (min, node.val), right gets (node.val, max) □ Use long/float boundaries to handle integer edge cases 4. FOR CONSTRUCTION PROBLEMS: □ Given sorted array → mid as root, recurse halves □ Given preorder → first element is root, partition by value □ Given inorder → combine with preorder/postorder to reconstruct 5. FOR RANGE PROBLEMS: □ Prune left subtree when node.val ≤ lo (all left values are too small) □ Prune right subtree when node.val ≥ hi (all right values are too large) □ Include node when lo ≤ node.val ≤ hi 6. EDGE CASES FOR BST: □ Empty tree → return null/0/false as appropriate □ Single node → check if it's the answer itself □ k > total nodes → return -1 or handle gracefully □ Integer overflow in validation → use long, not int □ Equal values → clarify: strict BST (no duplicates) or allow?
Pattern Recognition Quick Reference
| Signal in Problem | Pattern | Key Technique |
|---|---|---|
| "find value", "search", "closest" | BST Property | Navigate using < / > comparison |
| "kth smallest", "k-th element ascending" | Inorder | Stop at kth node visited |
| "kth largest", "k-th element descending" | Reverse inorder | Stop at kth node visited |
| "validate BST", "is BST valid" | Inorder + check | prev < curr; or [min, max] range |
| "sorted output", "merge BSTs" | Inorder collect | Inorder → array; merge sort step |
| "sum/count in range [lo, hi]" | Range + pruning | Skip subtrees outside range |
| "trim to range", "remove outside range" | Range recursion | Return opposite subtree when out of range |
| "LCA in BST" | BST Property | Both < node → left; both > node → right |
| "convert sorted → BST" | Construction | Mid as root, recurse halves |
| "recover BST" | Inorder violations | Find two violations; swap first and last |
| "BST iterator" | Lazy stack | Push left spine; pop + push right's left spine |
| "distance k from node" | Parent map + BFS | Build parent map, then BFS outward |
| "greater sum tree" | Reverse inorder | Running sum from largest to smallest |
Difficulty Progression Reference
| Stage | Characteristics | Representative Problems |
|---|---|---|
| Foundation | Single BST property step, O(h) | Search, Insert, LCA of BST |
| Early Intermediate | Inorder counting/stopping | Kth Smallest, Validate BST, BST Iterator |
| Intermediate | Range queries, construction | Range Sum, Trim BST, Sorted Array to BST |
| Late Intermediate | Multi-step + construction | Recover BST, Serialize BST, Greater Sum Tree |
| Advanced | Multi-BST, parent pointers, hard transforms | All Nodes at Distance K, Largest BST Subtree, Merge Two BSTs |
Common Interview Topics by Company Focus
Product-based companies (FAANG-tier):
- ›Validate BST — nearly universal
- ›Kth Smallest Element — core BST traversal
- ›LCA of BST — BST-specific vs general LCA contrast
- ›Serialize and Deserialize BST — design + traversal combination
- ›All Nodes at Distance K — multi-technique problem
- ›Recover BST — inorder violation detection
- ›Convert Sorted Array to BST — construction
Service-based and on-campus:
- ›Search, Insert, Delete in BST — fundamentals
- ›Inorder Successor/Predecessor — traversal mechanics
- ›Floor and Ceiling — BST property application
- ›Range Sum of BST — pruning technique
Startup and mid-size tech:
- ›BST Iterator — design interview
- ›Balance a BST — construction + inorder
- ›Two Sum in BST — set + traversal combo
- ›Largest BST Subtree — postorder aggregation
Progress Tracking
After solving each BST problem, record:
- ›Pattern — which of the 6 patterns does this belong to?
- ›BST property used — did you eliminate subtrees (O(h)) or traverse all (O(n))?
- ›Traversal direction — inorder, reverse inorder, preorder, or BST property traversal?
- ›Edge cases handled — empty tree, single node, k > n, integer overflow?
- ›Time/space achieved — O(h), O(log n), O(n), O(k)?
- ›Time to solve — target 15-20 minutes for easy, 25-30 minutes for medium
The decisive signal that BST pattern recognition is working: when you read "kth smallest element in BST" and immediately think "inorder traversal, stop at k — O(h + k) with iterative stack, O(k) amortised per call" — before reading the constraints or examples.
Problem: find the 'closest value to target' in a BST. Which approach achieves O(h) time?