Binary search tree
medium 18 minA binary search tree keeps every key in order: for each node, all keys in its left subtree are smaller and all keys in its right subtree are larger.
See it run
Follow one comparison per level as the tree searches, inserts, deletes in all three cases, lists itself in sorted order and checks its own rule.
Operations
Search
Look for a value by comparing it with one node per level: equal means found, smaller means go left, larger means go right. Each move throws away a whole subtree.
Step 1 of 8
Search for 37
target = 37
A balanced tree of 7 keys. Every node has smaller keys on its left and larger keys on its right, all the way down. We look for 37, starting at the root.
Step 1: Search for 37
def search(root, target): node = root while node: if target == node.val: return node # found it if target < node.val: node = node.left # smaller: only the left subtree can hold it else: node = node.right # larger: only the right subtree can hold it return None # fell off the tree: not present- Time
- O(h): O(log n) balanced, O(n) skewed
- Space
- O(1) iterative, O(h) recursive
- vs unsorted list
- O(n) scan
- vs sorted array
- O(log n), same idea
- 7-node tree
- ≤ 3 comparisons
Say the rule out loud at each node: equal, found; smaller, left; larger, right. It is binary search on a sorted array, drawn as a tree.
In the real world
The same binary search tree doing real jobs. Pick one and step through it.
Words compare alphabetically, so they fit in a BST just like numbers. Looking a word up is the phone-book move: earlier in the alphabet, go left; later, go right.
Step 1 of 4
Seven words
7 words
The words were added in the order mango, grape, pear, apple, kiwi, orange, plum. Everything left of mango comes earlier in the alphabet, everything right comes later.
Step 1: Seven words
root = Nonefor w in ["mango", "grape", "pear", "apple", "kiwi", "orange", "plum"]: root = insert(root, w) # strings compare alphabeticallyprint(search(root, "kiwi") is not None) # Trueroot = insert(root, "lime")out = []inorder(root, out)print(out) # ['apple', 'grape', 'kiwi', 'lime', 'mango', 'orange', 'pear', 'plum']Common mistakes
The bugs interviewers watch for, with the fix beside each.
Validating against the children only
criticalThe rule is about whole subtrees. A node can be larger than its parent and still sit on the wrong side of its grandparent, like 55 under 30 under 50. Pass the allowed range down, or check that the inorder sequence is strictly increasing.
Wrongdef is_valid(node): if node is None: return True if node.left and node.left.val >= node.val: return False if node.right and node.right.val <= node.val: return False return is_valid(node.left) and is_valid(node.right) # misses 55 under 30 under 50Rightdef is_valid(node, low=float("-inf"), high=float("inf")): if node is None: return True if not (low < node.val < high): return False return (is_valid(node.left, low, node.val) and is_valid(node.right, node.val, high))Two-children delete done wrong
criticalLifting one child into the gap loses the other subtree or breaks the order. Copy the inorder successor's value into the node, then delete the successor from the right subtree. Forgetting that second delete leaves the value in the tree twice.
Wrong# node has two childrenroot.val = succ.valreturn root # the successor is still down there: duplicate keyRightsucc = root.rightwhile succ.left: succ = succ.leftroot.val = succ.valroot.right = delete(root.right, succ.val) # remove the original successorreturn rootDropping the returned root
majorRecursive insert and delete return the new root of each subtree. If you call them without storing the result, an insert into an empty tree does nothing, and deleting the root leaves the old root in place.
Wrongroot = Noneinsert(root, 50) # result thrown away: root is still Nonedelete(root, 50) # deleting the root: the tree never sees itRightroot = Noneroot = insert(root, 50)root = delete(root, 50)# and inside: root.left = insert(root.left, val)Assuming O(log n)
majorA plain BST is only as fast as it is short. Inserting sorted keys builds a chain where every operation is O(n), and building it costs O(n²). Say O(h), and reach for a self-balancing tree when the input order is not random.
Wrongroot = Nonefor k in range(100000): # sorted keys root = insert(root, k) # chain: O(n^2) total, and RecursionErrorRightimport randomkeys = list(range(100000))random.shuffle(keys) # or use a balanced tree / sortedcontainersroot = Nonefor k in keys: root = insert(root, k) # expected height O(log n)No rule for duplicates
minorIf equal keys sometimes go left and sometimes right, search can miss them and validation becomes ambiguous. Decide up front: reject duplicates, keep a count in the node, or always send equal keys the same way (and use <= in the check on that side).
Wrongif val < root.val: root.left = insert(root.left, val)else: # equal goes right here... root.right = insert(root.right, val)# ...but search treats equal as "found" and validation uses strict <Rightif val < root.val: root.left = insert(root.left, val)elif val > root.val: root.right = insert(root.right, val)else: root.count += 1 # one node per key, with a countTouching None
minorAn empty tree is a valid input. Reading
node.leftwhen node is None raises AttributeError. Check for None before following a pointer, and decide what min or max of an empty tree should return.Wrongdef find_min(node): while node.left: # AttributeError when node is None node = node.left return node.valRightdef find_min(node): if node is None: return None # empty tree while node.left: node = node.left return node.val
Interview tips
How to explain it
- A binary tree where every node's left descendants are smaller and right descendants are larger.
- Search, insert and delete walk one root-to-leaf path: O(h), which is O(log n) balanced and O(n) skewed.
- Inorder traversal gives sorted order. Versus a hash table: a BST keeps order, a hash table gives O(1) average lookup.
Spot it in problems
- Inorder is sorted: kth smallest, validate, minimum difference between nodes.
- Range queries and closest-value searches: prune subtrees with the BST rule.
- Recursion with min and max bounds; an iterator built from a stack of left spines.
Memory tricks
- Left is Less, Right is moRe.
- Delete cases L-O-T: Leaf, One child, Two children.
- Inorder successor: go right once, then left all the way.
Watch out
- Always ask: can there be duplicate values?
- Edge cases: empty tree, single node, deleting the root, skewed trees.
- Mention balancing (AVL, red-black) whenever you quote O(log n).