Binary search trees: search, insert and validate
The ordering rule of a BST, why search takes O(h), and the classic validation trap that trips up most candidates.
In short
In a binary search tree every node is bigger than everything in its left subtree and smaller than everything in its right. Search, insert and delete follow one path: O(h), which is O(log n) if balanced and O(n) if it degenerates into a chain.
Search by discarding half
It is binary search on a tree: compare with the node, and the answer can only be in one subtree. Try the degenerate insert order to see why the shape matters.
1def search(node, target):2 while node:3 if target == node.val:4 return node5 if target < node.val:6 node = node.left7 else:8 node = node.right9 return None
Variables
Operations and shapes
| Operation | Balanced | Degenerate chain |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Sorted order | Inorder, O(n) | Inorder, O(n) |
Inserting already-sorted values builds a chain. Self-balancing trees (AVL, red-black) keep the height at log n; in practice they power TreeMap in Java and ordered sets elsewhere.
The classic trap: validating a BST
Checking only left < node < right for each node is wrong: a node deep in the left subtree can still be bigger than the root. Each node must fit inside a range inherited from all its ancestors.
def is_valid(node, lo=float('-inf'), hi=float('inf')):
if not node: return True
if not (lo < node.val < hi): return False
return (is_valid(node.left, lo, node.val) and
is_valid(node.right, node.val, hi))Key takeaways
- 01BST rule: left subtree < node < right subtree, at every node.
- 02Search, insert, delete cost O(h): log n if balanced, n if a chain.
- 03Validate with a (lo, hi) range, not just the two children.
- 04Inorder traversal of a BST is sorted.
Check your understanding
1 of 3
Search in a balanced BST costs…
Related topics
Traversals
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
9 min read →Binary search
If the data is sorted (or the answer is monotonic), look at the middle and throw away the half that can't contain the answer. Each step halves the problem: O(log n).
9 min read →