DSA Tutorial
🔍

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.

ProblemDifficultyRecognition ClueKey Insight
Search in BSTEasy"find target value in BST"Go left if target < node, right if target > node
Closest Value to TargetEasy"closest value to k in BST"Track closest seen; BST property guides direction
Floor in BSTMedium"largest value ≤ k"Record node when k > node.val, keep going right
Ceiling in BSTMedium"smallest value ≥ k"Record node when k < node.val, keep going left
Insert into BSTEasy"insert value maintaining BST property"Search for null position; insert as leaf
Delete from BSTMedium"delete node from BST"Leaf: remove; one child: replace; two children: replace with inorder successor
LCA of BSTEasy"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.

ProblemDifficultyRecognition ClueKey Insight
Kth Smallest Element in BSTMedium"kth smallest in BST"Inorder traversal, stop at k-th node
Validate BSTMedium"is this a valid binary search tree"Inorder + check prev < curr; or range [min, max] traversal
Convert BST to Sorted ArrayEasy"BST to sorted list/array"Collect inorder traversal into array
Inorder Successor in BSTMedium"next larger element of node p"If right subtree exists: leftmost of right; else deepest ancestor where went left
Inorder Predecessor in BSTMedium"next smaller element of node p"If left subtree exists: rightmost of left; else deepest ancestor where went right
BST IteratorMedium"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 ListMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Kth Largest Element in BSTMedium"kth largest in BST"Reverse inorder, stop at k-th node
Convert BST to Greater Sum TreeMedium"replace each node with sum of all greater values"Reverse inorder + running cumulative sum
Sum of BST Values Greater Than kEasy"sum of all values > k in BST"Reverse inorder, stop accumulating when node.val ≤ k
Decreasing Key TraversalEasy"traverse BST in non-increasing order"Reverse inorder directly
Convert BST to Min HeapHard"restructure BST into min-heap"Collect inorder sorted array, build heap
BST to Max HeapHard"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.

ProblemDifficultyRecognition ClueKey Insight
Range Sum of BSTEasy"sum of values in [lo, hi]"Skip left if node.val ≤ lo; skip right if node.val ≥ hi
Count Nodes in RangeEasy"count values in [lo, hi]"Same pruning as range sum; count instead of sum
Find Mode(s) in BSTEasy"most frequent values in BST"Inorder gives sorted sequence; count consecutive equal runs
Find All Duplicates in BSTEasy"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 ForestMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Convert Sorted Array to BSTEasy"sorted array → balanced BST"Mid as root; recurse on left and right halves
Convert Sorted List to BSTMedium"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 BSTMedium"convert unbalanced BST to balanced"Inorder to sorted array; build balanced BST from array
Serialize and Deserialize BSTMedium"encode BST to string and rebuild"Preorder serialize (no null needed); BST property for deserialize
Merge Two BSTsHard"merge two BSTs into one BST"Inorder both → merge sorted arrays → build from sorted
Build BST from Preorder TraversalMedium"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 BSTsHard"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.

ProblemDifficultyRecognition ClueKey Insight
All Nodes at Distance K from TargetHard"nodes exactly k edges from target (in any direction)"BFS from target using parent pointers to go upward
Largest BST SubtreeHard"largest subtree that is a valid BST"Postorder: each node returns (isBST, min, max, size); propagate upward
Two Nodes with Given Sum in BSTEasy"two nodes summing to k"HashSet + inorder; or two iterators from both ends
Count BST Nodes in RangeMedium"count nodes in range [lo, hi] given node count is known"BST property traversal with range checks
Pairs with Difference k in BSTMedium"find all pairs with value difference = k"Inorder → sorted array → two pointer
Median of BSTMedium"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 ProblemPatternKey Technique
"find value", "search", "closest"BST PropertyNavigate using < / > comparison
"kth smallest", "k-th element ascending"InorderStop at kth node visited
"kth largest", "k-th element descending"Reverse inorderStop at kth node visited
"validate BST", "is BST valid"Inorder + checkprev < curr; or [min, max] range
"sorted output", "merge BSTs"Inorder collectInorder → array; merge sort step
"sum/count in range [lo, hi]"Range + pruningSkip subtrees outside range
"trim to range", "remove outside range"Range recursionReturn opposite subtree when out of range
"LCA in BST"BST PropertyBoth < node → left; both > node → right
"convert sorted → BST"ConstructionMid as root, recurse halves
"recover BST"Inorder violationsFind two violations; swap first and last
"BST iterator"Lazy stackPush left spine; pop + push right's left spine
"distance k from node"Parent map + BFSBuild parent map, then BFS outward
"greater sum tree"Reverse inorderRunning sum from largest to smallest

Difficulty Progression Reference

StageCharacteristicsRepresentative Problems
FoundationSingle BST property step, O(h)Search, Insert, LCA of BST
Early IntermediateInorder counting/stoppingKth Smallest, Validate BST, BST Iterator
IntermediateRange queries, constructionRange Sum, Trim BST, Sorted Array to BST
Late IntermediateMulti-step + constructionRecover BST, Serialize BST, Greater Sum Tree
AdvancedMulti-BST, parent pointers, hard transformsAll 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:

  1. Pattern — which of the 6 patterns does this belong to?
  2. BST property used — did you eliminate subtrees (O(h)) or traverse all (O(n))?
  3. Traversal direction — inorder, reverse inorder, preorder, or BST property traversal?
  4. Edge cases handled — empty tree, single node, k > n, integer overflow?
  5. Time/space achieved — O(h), O(log n), O(n), O(k)?
  6. 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.

Suggested Quiz

Problem: find the 'closest value to target' in a BST. Which approach achieves O(h) time?

1/6
BST Practice Problems