Binary Search Trees
Use the BST ordering property for O(h) search, insert and delete, validate BSTs, and understand why balanced trees guarantee O(log n).
Intermediate · about 5 hours · difficulty 3/5
Learn first: Binary Trees and Traversals
A binary search tree keeps every value in the left subtree smaller than the node and every value in the right subtree larger. This makes search, insert and delete O(h), where h is the height.
Key operations
- Search / insert: go left or right by comparison.
- Delete: three cases. A leaf is removed directly, a node with one child is replaced by it, and a node with two children is replaced by its inorder successor (smallest in the right subtree), which is then deleted.
- Inorder traversal yields sorted order, which solves k-th smallest, validate BST and two-sum-in-BST.
- Floor / ceiling, successor / predecessor by walking and remembering the last candidate.
Balance
Inserting sorted data creates a linked-list-shaped tree with h = n. Self-balancing trees (AVL, red-black) rotate nodes to keep h = O(log n). You rarely implement them in interviews, but you should know that std::map, TreeMap and std::set are red-black trees, which is why their operations are O(log n).
Pitfalls
Validating a BST by only comparing a node with its direct children is wrong; you must pass down a valid (min, max) range or check that the inorder sequence is strictly increasing. Watch for duplicates and integer overflow when using INT_MIN/INT_MAX as bounds (use long or null).
Key concepts
- BST property and search
- Insert and delete
- Validate BST with ranges
- Inorder as sorted order
- Floor, ceil, successor
- AVL and red-black trees (concepts)
- BST iterator
Mini project
Implement a BST class with insert, search, delete and inorder, then solve: Validate BST, Kth Smallest Element in a BST, LCA of a BST, Delete Node in a BST, Convert Sorted Array to BST, BST Iterator, and Two Sum IV.
Check yourself
Why does checking only node.left.val < node.val < node.right.val at every node fail to validate a BST? Give a counterexample.
Free resources
- VisuAlgo: Binary Search Tree (VisuAlgo)
- Binary search tree (GeeksforGeeks)
- Data Structure Visualizations (USFCA) (USFCA)