Binary Search Trees
Trees with an ordering rule: smaller values to the left, larger to the right.
- current
- read by this step
- visited / done
- ruled out
- result
Both smaller than 6
3 and 5 are both less than 6, so their ancestor must be in the left subtree.
VARIABLES
- node
- 6
- p
- 3
- q
- 5
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
In a BST, every node’s left subtree holds smaller values and its right subtree larger ones. An inorder traversal visits the values in sorted order.
Why it matters
The ordering lets search, insert and delete skip half the tree at each step - as long as the tree stays balanced.
Think of it like this
A “higher or lower” guessing game where each answer sends you down one branch.
Use it when
- Ordered data with frequent inserts and lookups
- Floor, ceiling or kth-smallest queries
- Lowest common ancestor using value comparisons
Avoid it when
- Data arriving in sorted order with no balancing - the tree becomes a list
- You only need membership - a hash set is simpler
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Search or insert (balanced) | O(log n) | O(h) |
| Search or insert (skewed) | O(n) | O(h) |
| Inorder traversal | O(n) | O(h) |
Often confused with: heaps - also trees, but they only guarantee parent ≤ children, not left < right.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- A BST’s inorder traversal is sorted - many problems reduce to that fact
- Validation needs a (low, high) range, not just parent comparisons
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Validating with only parent–child comparisons - deeper violations slip through
- Ignoring duplicates - decide which side they go on
- Assuming O(log n) without balancing
Edge cases to test
- p or q is itself the ancestor
- A single-node tree
- A skewed tree built from sorted inserts
Knowledge check
Quick check to lock in the intuition.
Why isn’t checking node.left.val < node.val < node.right.val enough to validate a BST?
Practice
Apply what you just watched on real interview problems.