Nearly every binary search tree interview question is solved by one of three ideas:
- Walk one path. At each node, the BST property tells you which side can contain the answer, so you go only left or only right: .
- Inorder is sorted. Turn “BST” into “sorted sequence” and use array techniques (kth element, two pointers, finding an out-of-order pair): .
- Carry a range down, or return facts up. Pass
(low, high)bounds to children, or return(min, max, size)to parents, to check the BST property over whole subtrees.
This page works through the 20 BST questions that come up most often, from easy to hard. Each one names the idea it uses, with a worked example, a C++ solution tested on the example tree, complexity, and the edge cases interviewers probe.
Tree & Graph series, step 4 of 8. You should know the BST basics (search, insert, the three deletion cases) and the general tree questions. Next: Tree Questions for University Exams.
The Example BST
Unless stated otherwise, every example uses the BST built by inserting 50, 30, 70, 20, 40, 60, 80, 65. Its inorder traversal is 20 30 40 50 60 65 70 80.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
| Difficulty | Questions | Foundational? |
|---|---|---|
| Easy | 1–5 search, insert, delete, min/max, validate | Yes: learn these first |
| Easy–Medium | 6–12 kth smallest/largest, LCA, predecessor/successor, sorted array → BST, floor/ceil, pair sum | Yes |
| Medium | 13–17 recover BST, range, closest value, successor of a node, delete all nodes | Common follow-ups |
| Hard | 18–20 build from preorder, BST → doubly linked list, largest BST subtree | Senior / competitive |
Easy: The Foundational Five
1. Search in a BST
Problem. Return the node with value target, or nullptr. Idea 1.
Example. search(65) follows 50 → 70 → 60 → 65.
TreeNode* searchBST(TreeNode* root, int target) {
while (root && root->val != target) {
root = target < root->val ? root->left : root->right;
}
return root;
}
time, space. Edge cases: empty tree; target smaller than the minimum or larger than the maximum (the walk ends at a null child).
2. Insert into a BST
Problem. Insert val (not already present) and return the root. Idea 1: the search for val ends exactly where it belongs.
Example. Insert 65 into the tree without it: 50 → 70 → 60 → right of 60 is empty → place it there.
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insertIntoBST(root->left, val);
} else {
root->right = insertIntoBST(root->right, val);
}
return root;
}
time. Edge cases: empty tree (the new node becomes the root, so the caller must use the return value); duplicates (state your policy).
3. Delete a node from a BST
Problem. Delete key if present and return the root (LeetCode 450).
Steps. Find the node. Leaf: return nullptr. One child: return that child. Two children: copy the inorder successor (minimum of the right subtree) into the node, then delete the successor from the right subtree. The full reasoning and diagrams for each case are in the BST guide.
TreeNode* deleteFromBST(TreeNode* root, int key) {
if (!root) {
return nullptr;
}
if (key < root->val) {
root->left = deleteFromBST(root->left, key);
} else if (key > root->val) {
root->right = deleteFromBST(root->right, key);
} else {
if (!root->left || !root->right) { // zero or one child
TreeNode* child = root->left ? root->left : root->right;
delete root;
return child;
}
TreeNode* successor = root->right; // two children
while (successor->left) {
successor = successor->left;
}
root->val = successor->val;
root->right = deleteFromBST(root->right, successor->val);
}
return root;
}
time. Edge cases: key not present; deleting the root; the successor having a right child. Follow-up: use the predecessor instead; delete without copying values (relink the successor node itself, needed when nodes carry large payloads).
4. Find the minimum and maximum
The minimum is the leftmost node; the maximum is the rightmost.
int bstMin(TreeNode* root) { // precondition: root != nullptr
while (root->left) {
root = root->left;
}
return root->val;
}
int bstMax(TreeNode* root) { // precondition: root != nullptr
while (root->right) {
root = root->right;
}
return root->val;
}
time. For the example: 20 and 80. Edge case: empty tree, so decide whether to throw, return an optional, or document the precondition as above.
5. Validate a BST
Problem. Is a binary tree a valid BST (LeetCode 98)? Idea 3.
The trap. In the right-hand tree every parent–child pair looks fine (6 < 15, 20 > 15), but 6 sits in 10’s right subtree, so it must be greater than 10. Checking only parent and children answers “valid”, which is wrong.
Intuition. Every node must lie inside an open interval inherited from its ancestors. Going left tightens the upper bound; going right tightens the lower bound.
bool validRange(TreeNode* node, long long low, long long high) {
if (!node) {
return true;
}
if (node->val <= low || node->val >= high) {
return false;
}
return validRange(node->left, low, node->val) && validRange(node->right, node->val, high);
}
bool isValidBST(TreeNode* root) {
return validRange(root, LLONG_MIN, LLONG_MAX);
}
time, space. Edge cases: values equal to INT_MIN/INT_MAX (hence long long bounds); duplicates (strict < rejects them). Alternative: inorder traversal must be strictly increasing; track only the previous value.
Easy–Medium: Core Patterns
6. Find the kth smallest element
Problem. Return the kth smallest key (1-indexed) (LeetCode 230). Idea 2.
Example. k = 3 → inorder 20 30 40 ... → 40 (diagram above).
Steps. Do an iterative inorder traversal and stop at the kth visited node, so you never touch the rest of the tree.
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* current = root;
while (current || !st.empty()) {
while (current) {
st.push(current);
current = current->left;
}
current = st.top();
st.pop();
if (--k == 0) {
return current->val; // kth node in sorted order
}
current = current->right;
}
return -1; // k larger than the number of nodes
}
time, space. Follow-up (very common): “The BST is modified often and kthSmallest is called often.” Store the size of each subtree in every node; then go left if k <= size(left), return the node if k == size(left) + 1, else go right with k - size(left) - 1: per query. This is an order-statistic tree.
7. Find the kth largest element
Idea 2, reversed. Reverse inorder (Right, Root, Left) visits keys in descending order.
int kthLargest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* current = root;
while (current || !st.empty()) {
while (current) {
st.push(current);
current = current->right;
}
current = st.top();
st.pop();
if (--k == 0) {
return current->val;
}
current = current->left;
}
return -1;
}
Example: k = 2 → 80, 70 → 70. time. Alternative: kth largest = (n − k + 1)th smallest, but that needs n first.
8. Lowest Common Ancestor in a BST
Problem. Find the LCA of two keys p and q that exist in the BST (LeetCode 235). Idea 1.
Intuition. If both keys are smaller than the current node, the LCA is in the left subtree; if both are larger, in the right subtree. Otherwise they split here (or one of them is this node), so this node is the LCA.
TreeNode* lcaBST(TreeNode* root, int p, int q) {
while (root) {
if (p < root->val && q < root->val) {
root = root->left;
} else if (p > root->val && q > root->val) {
root = root->right;
} else {
return root;
}
}
return nullptr;
}
Examples: LCA(20, 40) = 30; LCA(65, 80) = 70; LCA(20, 65) = 50; LCA(60, 65) = 60 (a node is its own ancestor). time, space, compared with for a general binary tree.
9. Find inorder predecessor and successor of a key
Problem. For a key (which may or may not be in the tree), find the largest key smaller than it and the smallest key larger than it.
Intuition. Walk from the root. Every time you go left, the node you left is a candidate successor (it is larger than the key). Every time you go right, it is a candidate predecessor. The last candidates seen are the closest ones.
// Returns {predecessor, successor}; INT_MIN / INT_MAX mean "none".
pair<int, int> predecessorSuccessor(TreeNode* root, int key) {
int pred = INT_MIN, succ = INT_MAX;
TreeNode* node = root;
while (node) { // successor: smallest value > key
if (key < node->val) {
succ = node->val;
node = node->left;
} else {
node = node->right;
}
}
node = root;
while (node) { // predecessor: largest value < key
if (key > node->val) {
pred = node->val;
node = node->right;
} else {
node = node->left;
}
}
return {pred, succ};
}
Examples: key 50 → (40, 60); key 65 → (60, 70); key 20 → (none, 30). time. Edge cases: smallest or largest key (one side is “none”); key not in the tree (still works).
10. Convert a sorted array into a balanced BST
Problem. Build a height-balanced BST from a sorted array (LeetCode 108).
Intuition. The middle element has half the elements on each side, so making it the root balances the tree. Apply the same rule to each half.
TreeNode* buildBalancedRange(const vector<int>& nums, int lo, int hi) {
if (lo > hi) {
return nullptr;
}
int mid = lo + (hi - lo) / 2; // avoids int overflow of (lo + hi)
TreeNode* root = new TreeNode(nums[mid]);
root->left = buildBalancedRange(nums, lo, mid - 1);
root->right = buildBalancedRange(nums, mid + 1, hi);
return root;
}
TreeNode* sortedArrayToBST(const vector<int>& nums) {
return buildBalancedRange(nums, 0, (int)nums.size() - 1);
}
time, recursion depth. Follow-ups: sorted linked list to BST (find middles with slow/fast pointers, or build in inorder using a moving list pointer for ); rebalance an existing BST (inorder to array, then this).
11. Floor and ceil of a value
Problem. Floor(x) = largest key ≤ x. Ceil(x) = smallest key ≥ x. Idea 1.
Example. floor(55) = 50, ceil(55) = 60, floor(65) = ceil(65) = 65, ceil(85) does not exist.
optional<int> bstFloor(TreeNode* root, int x) {
optional<int> best;
while (root) {
if (root->val == x) {
return x;
}
if (root->val < x) { // candidate, look for larger
best = root->val;
root = root->right;
}
else {
root = root->left;
}
}
return best;
}
optional<int> bstCeil(TreeNode* root, int x) {
optional<int> best;
while (root) {
if (root->val == x) {
return x;
}
if (root->val > x) { // candidate, look for smaller
best = root->val;
root = root->left;
} else {
root = root->right;
}
}
return best;
}
time. std::optional (C++17) expresses “no answer” without a magic number. This is exactly what std::set::lower_bound (ceil) does internally.
12. Find a pair with a given sum
Problem. Do two different nodes add up to target (LeetCode 653)? Idea 2.
Example. target 100: 20 + 80 → true. target 1000 → false.
Steps. Get the sorted inorder sequence, then use two pointers from both ends: if the sum is too small move the left pointer right, if too large move the right pointer left.
void collectInorder(TreeNode* node, vector<int>& out) {
if (!node) {
return;
}
collectInorder(node->left, out);
out.push_back(node->val);
collectInorder(node->right, out);
}
bool findTarget(TreeNode* root, int target) {
vector<int> sorted;
collectInorder(root, sorted);
int i = 0, j = (int)sorted.size() - 1;
while (i < j) {
long long sum = (long long)sorted[i] + sorted[j];
if (sum == target) {
return true;
}
if (sum < target) {
++i;
} else {
--j;
}
}
return false;
}
time and space. Follow-up: reduce space to with two BST iterators (one forward inorder stack, one reverse) moving toward each other.
Medium
13. Recover a BST where two nodes were swapped
Problem. Exactly two nodes’ values were swapped by mistake. Fix the tree without changing its structure (LeetCode 99). Idea 2.
Example. Swap 30 and 65 in our tree. Inorder becomes 20 65 40 50 60 30 70 80.
Steps. In a sorted sequence with two elements swapped there are one or two drops (a value smaller than the one before it):
- First drop: 65 > 40. The first wrong node is the larger one, 65.
- Second drop: 60 > 30. The second wrong node is the smaller one, 30.
- If there is only one drop (adjacent swap), the two nodes of that drop are the answer.
Swap the values of the first and second nodes.
void findSwapped(TreeNode* node, TreeNode*& prev, TreeNode*& first, TreeNode*& second) {
if (!node) {
return;
}
findSwapped(node->left, prev, first, second);
if (prev && prev->val > node->val) { // a drop in the inorder sequence
if (!first) {
first = prev;
}
second = node;
}
prev = node;
findSwapped(node->right, prev, first, second);
}
void recoverTree(TreeNode* root) {
TreeNode *prev = nullptr, *first = nullptr, *second = nullptr;
findSwapped(root, prev, first, second);
if (first && second) {
swap(first->val, second->val);
}
}
time, space. Follow-up: the -space version uses Morris inorder traversal.
14. Find all values in a range
Problem. Return all keys in [low, high] in sorted order (or their sum, LeetCode 938).
Intuition. Inorder traversal with pruning: only go left if smaller keys could still be in range, only go right if larger keys could be.
void rangeCollect(TreeNode* node, int low, int high, vector<int>& out) {
if (!node) {
return;
}
if (node->val > low) {
rangeCollect(node->left, low, high, out); // smaller keys may qualify
}
if (node->val >= low && node->val <= high) {
out.push_back(node->val);
}
if (node->val < high) {
rangeCollect(node->right, low, high, out); // larger keys may qualify
}
}
Example: range [35, 65] → 40 50 60 65. time, where is the number of keys reported.
15. Find the value closest to a target
Problem. Return the key with the smallest absolute difference from a (possibly non-integer) target (LeetCode 270).
int closestValue(TreeNode* root, double target) {
int best = root->val; // precondition: non-empty tree
while (root) {
if (abs(root->val - target) < abs(best - target)) {
best = root->val;
}
root = target < root->val ? root->left : root->right;
}
return best;
}
Example: target 62 → candidates on the path 50, 70, 60, 65 → 60 (distance 2). time. Why does one path suffice? The closest key is either the floor or the ceil of the target, and both lie on the search path. Follow-up: k closest values (LeetCode 272): inorder plus a sliding window of size k, or two stacks.
16. Inorder successor of a given node
Problem. Given a pointer p to a node in the BST (no parent pointers), return the node with the next larger key (LeetCode 285).
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* succ = nullptr;
while (root) {
if (p->val < root->val) {
succ = root;
root = root->left;
} else {
root = root->right;
}
}
return succ;
}
Examples: successor of 40 → 50 (an ancestor); successor of 60 → 65 (in the right subtree); successor of 80 → nullptr. . Follow-up with parent pointers: if p has a right child, return the minimum of the right subtree; otherwise climb until you arrive from a left child.
17. Delete all nodes in a BST
Problem. Free every node and leave the root as nullptr.
Intuition. Children must be freed before their parent (postorder); otherwise you lose the pointers to them.
void deleteAll(TreeNode*& root) {
if (!root) {
return;
}
deleteAll(root->left);
deleteAll(root->right);
delete root;
root = nullptr; // the caller's pointer no longer dangles
}
time, space. Taking TreeNode*& lets the function reset the caller’s pointer. Follow-ups: iterative version for very deep trees; with std::unique_ptr children, destruction is automatic (but recursive, so a very deep chain can still overflow the stack). A related question, trim a BST to [low, high] (LeetCode 669), deletes only the nodes outside a range.
Hard
18. Construct a BST From Preorder Traversal
Problem. Rebuild a BST from its preorder sequence (LeetCode 1008).
Example. preorder 50 30 20 40 70 60 65 80 → our example tree.
Intuition. Unlike a general binary tree, a BST needs no inorder sequence: inorder is just the sorted keys. Better still, pass an upper bound: consume the next preorder value as a node only if it fits under the current bound.
TreeNode* buildPreorder(const vector<int>& pre, size_t& next, long long bound) {
if (next == pre.size() || pre[next] > bound) {
return nullptr;
}
TreeNode* root = new TreeNode(pre[next++]);
root->left = buildPreorder(pre, next, root->val); // left keys must be < root
root->right = buildPreorder(pre, next, bound); // right keys keep the parent's bound
return root;
}
TreeNode* bstFromPreorder(const vector<int>& preorder) {
size_t next = 0;
return buildPreorder(preorder, next, LLONG_MAX);
}
Complexity. : every value is consumed once. Inserting each value one by one also works but is in the worst case. Follow-up: from postorder, process from the end with a lower bound, building the right subtree first.
19. Convert a BST into a sorted doubly linked list
Problem. Rearrange pointers in place so that left means “previous” and right means “next”, in sorted order. Return the head (LeetCode 426 asks for a circular list; this version is linear).
Intuition. Inorder visits nodes in sorted order. Keep a prev pointer; when visiting a node, link prev->right = node and node->left = prev.
void linkInorder(TreeNode* node, TreeNode*& prev, TreeNode*& head) {
if (!node) {
return;
}
linkInorder(node->left, prev, head);
if (prev) {
prev->right = node;
} else {
head = node; // first visited node is the head
}
node->left = prev;
prev = node;
linkInorder(node->right, prev, head);
}
TreeNode* bstToDoublyList(TreeNode* root) {
TreeNode *prev = nullptr, *head = nullptr;
linkInorder(root, prev, head);
if (prev) {
prev->right = nullptr; // tail
}
return head;
}
Result: 20 ⇄ 30 ⇄ 40 ⇄ 50 ⇄ 60 ⇄ 65 ⇄ 70 ⇄ 80. time, space, no new nodes. Is it safe to overwrite node->right during the traversal? Yes: we only set prev->right, and prev’s right subtree has already been fully visited by then. Circular version: at the end, link head->left = prev and prev->right = head.
20. Find the largest BST subtree in a binary tree
Problem. In an arbitrary binary tree, find the size of the largest subtree that is a valid BST (LeetCode 333). Idea 3, upward.
Example. Tree 10(5(1, 8), 15(-, 7)): the subtree at 5 (1, 5, 8) is a BST of size 3; the subtree at 15 is not (7 < 15 on the right); the whole tree is not. Answer: 3.
Intuition. A naïve solution validates every subtree separately: . Instead, do one postorder pass where each node returns facts about its subtree: is it a BST, its size, its minimum and maximum. A node forms a BST if both children do and left.max < node < right.min.
struct SubtreeInfo {
bool isBST;
int size;
long long minVal, maxVal;
};
SubtreeInfo largestBSTInfo(TreeNode* node, int& best) {
if (!node) {
return {true, 0, LLONG_MAX, LLONG_MIN}; // empty: neutral min/max
}
SubtreeInfo L = largestBSTInfo(node->left, best);
SubtreeInfo R = largestBSTInfo(node->right, best);
if (L.isBST && R.isBST && L.maxVal < node->val && node->val < R.minVal) {
int size = L.size + R.size + 1;
best = max(best, size);
return {true, size, min<long long>(L.minVal, node->val), max<long long>(R.maxVal, node->val)};
}
return {false, 0, 0, 0};
}
int largestBSTSubtree(TreeNode* root) {
int best = 0;
largestBSTInfo(root, best);
return best;
}
time, space. The empty subtree returns min = +∞, max = −∞ so that any node passes the comparison against a missing child. Follow-up: return the maximum sum BST subtree (LeetCode 1373) with the same structure.
Quick Revision Table
| # | Question | Idea | Time |
|---|---|---|---|
| 1, 2, 3 | Search / insert / delete | One path | |
| 4 | Min / max | One path | |
| 5 | Validate | Range down | |
| 6, 7 | Kth smallest / largest | Inorder, stop early | |
| 8 | LCA | One path, split point | |
| 9, 16 | Predecessor / successor | One path, remember candidates | |
| 10 | Sorted array → BST | Middle as root | |
| 11, 15 | Floor / ceil / closest | One path | |
| 12 | Pair sum | Inorder + two pointers | |
| 13 | Recover swapped | Inorder drops | |
| 14 | Range | Pruned inorder | |
| 17 | Delete all | Postorder | |
| 18 | From preorder | Upper bound | |
| 19 | To doubly linked list | Inorder relinking | |
| 20 | Largest BST subtree | Facts up (postorder) |
Remember that is only if the tree is balanced; say ”, which is for a balanced BST” in interviews.
Frequently Asked Questions
Which BST questions are asked most often?
Validate BST, kth smallest, LCA in a BST, delete a node, and sorted array to BST appear constantly in interview prep lists. They are also the building blocks for the medium and hard questions above, so learn them first.
Why does my validate-BST solution fail on LeetCode?
Usually one of two bugs: comparing only with direct children (see question 5), or using int bounds initialised to INT_MIN/INT_MAX while the tree contains those exact values.
Should I use std::set in an interview?
If the problem is about using an ordered collection, yes: std::set is a balanced BST with lower_bound (ceil) and upper_bound. If the problem gives you a TreeNode*, it wants you to work on the tree itself.
Next Steps
- Next: Tree Questions for University Exams in Bangladesh.
- Then BST Questions for University Exams in Bangladesh, with insertion and deletion traces.
- Moving on to graphs: What Are DFS and BFS?