synopsis · Trees & graphs · chapter 23
Binary Search Trees
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A binary tree with one promise at every node: left subtree < node < right subtree. Inorder (left, node, right) reads the values sorted.
- use it when
Sorted order or nearest-key questions on a changing set: floor/ceiling, kth smallest, successor, bookings. Handed a BST? Think inorder or a one-path walk.
- template
One-path walk:
while (cur != null) cur = x < cur.val ? cur.left : cur.right;— search, insert, LCA and successor all start here. - cost
Search/insert/delete/floor = O(h). Balanced: h ≈ log₂ n (20 levels for 10 lakh keys). Sorted inserts into a plain BST: h = n − 1. TreeMap guarantees O(log n).
- trap
Checking only
left.val < node.val < right.valmisses grandchildren. Pass (low, high) bounds down — asnull/long, neverInteger.MIN_VALUEsentinels. - trap
Recursive insert/delete must re-link:
root.left = deleteNode(root.left, key);Drop the assignment and the change is lost. - pro tip
Delete with two children: copy the in-order successor (leftmost of the right subtree), then delete it from the right subtree — it has no left child.
- pro tip
Successor/ceiling: every node bigger than x is a candidate — remember it and go left. The last candidate wins. O(h), O(1) space.
- pro tip
TreeMap/TreeSetare red-black BSTs:floorKey≤,ceilingKey≥,lowerKey<,higherKey>. All returnnullwhen nothing qualifies.
Shaky on a card? Open the chapter or flip its recall cards.