Welcome to Day 9 of your coding interview journey.
Yesterday, we introduced Binary Trees.
Today, we take it one step further into a specialized and very important structure:
π Binary Search Trees (BSTs)
π§ What is a Binary Search Tree?
A Binary Search Tree (BST) is a binary tree with a special property:
π For every node:
- All values in the left subtree are smaller
- All values in the right subtree are larger
Example:
5
/ \
3 7
/ \ \
2 4 8
π Why BSTs Matter
BSTs allow efficient operations:
- Search β O(log n)
- Insert β O(log n)
- Delete β O(log n)
π (In balanced cases)
β οΈ Important Note
BST problems often test:
- Tree traversal
- Recursion
- Understanding constraints (not just structure!)
π‘ Problem 1 β Validate Binary Search Tree
π§© Problem
Given the root of a binary tree:
π Determine if it is a valid BST
β Common Mistake
Many people only compare:
node.left < node < node.right
β This is NOT enough!
π§ Key Insight
Each node must respect a range:
- Left subtree β
(min, node.val) - Right subtree β
(node.val, max)
π οΈ Solution in Python
def is_valid_bst(root):
def helper(node, low, high):
if not node:
return True
if not (low < node.val < high):
return False
return (
helper(node.left, low, node.val) and
helper(node.right, node.val, high)
)
return helper(root, float("-inf"), float("inf"))
β‘ Complexity
- Time:
O(n) - Space:
O(h)
π― Key Insight
π Always think in ranges, not just parent-child comparisons
π‘ Problem 2 β Lowest Common Ancestor (LCA) in BST
π§© Problem
Given a BST and two nodes p and q:
π Find their lowest common ancestor
(The lowest node that has both as descendants)
Example:
6
/ \
2 8
/ \
0 4
/ \
3 5
π LCA of 2 and 8 β 6
π LCA of 3 and 5 β 4
π§ Key Insight (BST Advantage)
Because it’s a BST:
- If both values are smaller β go left
- If both are larger β go right
- Otherwise β current node is the LCA
π οΈ Solution in Python
def lowest_common_ancestor(root, p, q):
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
β‘ Complexity
- Time:
O(h) - Space:
O(1)(iterative)
π― Why This Works
π BST property lets us skip entire subtrees
This is much faster than general binary tree solutions.
β οΈ Common Mistakes
- β Ignoring BST properties
- β Using generic tree logic (slower)
- β Forgetting edge cases (same node, root as LCA)
- β Not validating full subtree ranges
π§ͺ Practice Problems
To master BSTs, try:
- Insert into BST
- Delete node in BST
- Kth smallest element in BST
- Convert sorted array to BST
- BST iterator
π― Key Takeaways
- BSTs = ordered trees
- Always leverage:
- Left < Node < Right
- Think in:
- Ranges (validation)
- Direction (search & LCA)
π Your Challenge (Day 9)
Solve this:
Find the Kth smallest element in a BST.
(Hint: in-order traversal π)
π Final Thoughts
BSTs are extremely common in interviews because they combine:
- Trees
- Searching
- Optimization
Mastering them puts you ahead of many candidates.