Binary Search Trees
Connect ordering invariants to lookup, insert, validation, range queries, and the cost of unbalanced shape.
What you will be able to do
A binary search tree is a binary tree with an ordering invariant: values in the left subtree are smaller, values in the right subtree are larger. That invariant enables search, sorted traversal, and range queries, but only if the tree shape stays reasonable.
The BST Invariant
The invariant applies to entire subtrees, not only direct children. Every node carries an allowed range. A right grandchild of the left child must still be less than the root.
Scenario: In-Memory Price Index
A marketplace keeps products ordered by price for quick range filters. A balanced search tree can support insert, lookup, and range traversal. But if inserts arrive sorted and the tree does not rebalance, it degenerates into a linked list.
| Operation | Balanced BST | Skewed BST |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Inorder traversal | Sorted O(n) | Sorted O(n) |
| Range query | O(log n + k) | O(n) worst case |
Same Pattern in Java, Python, and JavaScript
BST search follows the invariant: target smaller goes left, target larger goes right.
class TreeNode { int value; TreeNode left; TreeNode right; }
class BstSearch {
static boolean contains(TreeNode node, int target) {
while (node != null) {
if (target == node.value) return true;
node = target < node.value ? node.left : node.right;
}
return false;
}
}Assessment trap
Checking only node.left < node < node.right is not enough. The full subtree must respect inherited min and max bounds.
Interview signalFrequently Asked Interview Questions
These are canonical interview patterns for this topic, phrased as concrete problem statements. They avoid vague theory questions and prepare you for the exact reasoning interviewers expect: invariant, edge cases, complexity, and trade-off.
- Return whether a binary tree is a valid BST.
- Return the kth smallest value in a BST.
- Return the sum of BST values between low and high inclusive.
Production practiceCompany-Style Practice Examples
These are not claimed as exact company-specific questions. They are the interview patterns repeatedly used by product companies to test whether you can move from brute force to a defensible implementation.
| Example | Brute-force approach | Stronger solution | Production notes |
|---|---|---|---|
| Price range filter | Scan every product for each range. | Use ordered traversal with range pruning in a balanced BST/index. | Cost depends on height plus returned items. |
| Validate imported index | Check only immediate children. | Validate with inherited lower and upper bounds. | Subtree violations are common interview traps. |
| Kth cheapest item | Dump all values then sort. | Use inorder traversal and stop at k. | BST order turns traversal into sorted sequence. |
Solved modelInterview Question Solutions
Question 1: Validate Binary Search Tree
Return whether a binary tree is a valid BST. Use inherited min/max bounds because every subtree must respect all ancestors, not just its parent.
class Node { int val; Node left; Node right; }
class ValidateBst {
static boolean isValid(Node root) {
return valid(root, null, null);
}
static boolean valid(Node node, Integer low, Integer high) {
if (node == null) return true;
if (low != null && node.val <= low) return false;
if (high != null && node.val >= high) return false;
return valid(node.left, low, node.val) && valid(node.right, node.val, high);
}
}Question 2: Kth Smallest in a BST
Return the kth smallest value in a BST. Inorder traversal visits BST values in sorted order. Stop when the kth value is reached.
import java.util.*;
class Node { int val; Node left, right; }
class KthSmallest { static int kth(Node root, int k) { Deque<Node> stack = new ArrayDeque<>(); Node cur = root; while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur); cur = cur.left; } cur = stack.pop(); if (--k == 0) return cur.val; cur = cur.right; } throw new IllegalArgumentException(); } }Question 3: Range Sum in a BST
Return the sum of BST values between low and high inclusive. Use the BST invariant to prune subtrees that cannot contain valid values.
class Node { int val; Node left, right; }
class RangeSum { static int sum(Node node, int low, int high) { if (node == null) return 0; if (node.val < low) return sum(node.right, low, high); if (node.val > high) return sum(node.left, low, high); return node.val + sum(node.left, low, high) + sum(node.right, low, high); } }Solved modelWorked Interview Answer
Validate whether a binary tree satisfies the full BST invariant. Carry inherited lower and upper bounds. Direct parent-child checks miss violations deeper inside a subtree.
class Node { int val; Node left; Node right; }
class ValidateBst {
static boolean isValid(Node root) {
return valid(root, null, null);
}
static boolean valid(Node node, Integer low, Integer high) {
if (node == null) return true;
if (low != null && node.val <= low) return false;
if (high != null && node.val >= high) return false;
return valid(node.left, low, node.val) && valid(node.right, node.val, high);
}
}Hands-on drillTry It Yourself
Practice task
Draw a tree that passes parent-child checks but fails the full BST invariant. Validate it using inherited min/max bounds.
Failure patternsCommon Mistakes to Avoid
- Checking only direct children.
- Ignoring duplicates policy.
- Assuming BST is balanced.
- Not using inorder sorted property.
- Using BST where hash lookup is enough and order is irrelevant.
Execution guardrailQuick-Start Checklist
- Define duplicate policy.
- Carry min and max bounds.
- Use inorder for sorted traversal.
- State cost in terms of height.
- Mention balance assumptions.
- For range query, prune impossible subtrees.
Recall drillKnowledge Check
| Question | Strong answer |
|---|---|
| Why is inorder traversal sorted? | Left subtree values come before node, then right subtree values. |
| What is validation with bounds? | Each node must lie inside inherited min/max limits. |
| What controls BST search cost? | Tree height. |
VocabularyKey Terms
| Term | Meaning |
|---|---|
| BST invariant | Left subtree less than node, right subtree greater than node, recursively. |
| Inorder | Left, node, right traversal. |
| Range query | Retrieve values between low and high. |
| Balanced tree | Tree with height O(log n). |
Next practiceFurther Reading
- Practice validate BST, kth smallest, LCA in BST, and range sum BST.
- Study AVL/red-black trees conceptually.
- Compare BSTs with hash maps and sorted arrays.