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.
Video lesson · Chapter 1 of 6
A word opens one door
Binary search trees — The turning vault
1:01Reel
Read caption
A scarab courier routes key sixty through a search-tree vault. The route exposes the ancestor constraint and the effect of height on search. Smaller goes left. Larger goes right. Every turn keeps every earlier promise.
How it works
Step through the idea, or press Play.
Compare at the node. Equal means found; smaller means the key can only be in the left subtree, larger only in the right
Understand it
Start here
What a binary search tree is
A binary search tree (BST) is a binary tree with one extra rule: for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. Think of a phone book: open it in the middle, and if the name you want comes earlier, you only ever look in the first half again.
A small BST
Left is less
Every key in a node's left subtree is smaller than the node.
Right is more
Every key in a node's right subtree is larger than the node.
Every subtree is a BST
The rule holds at every node, so each subtree is a smaller BST. That is why the code is naturally recursive.
The invariant
The rule is about whole subtrees
The BST property
Operation 1
Search: one comparison per level
Searching for a target
In the tree above, searching for 6: at 8, , go left; at 3, , go right; at 6, found. 3 comparisons instead of checking all 7 nodes. Searching for 7 would go 8, 3, 6, then fall off at 6.right and return None.
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef search(root, target): # recursive: O(h) stack if root is None or root.val == target: return root if target < root.val: return search(root.left, target) return search(root.right, target)def search_iter(root, target): # iterative: O(1) space node = root while node and node.val != target: node = node.left if target < node.val else node.right return noderoot = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(10, TreeNode(9), TreeNode(14)))print(search(root, 6).val, search_iter(root, 7)) # 6 NoneOperation 2
Insert: search, then fill the empty slot
Inserting a value
| Tree (insertion order) | Insert | Path | Lands as |
|---|---|---|---|
| 50, 30, 70, 20, 40 | 35 | 50 → 30 → 40 | left child of 40 |
| 50, 25, 75, 12, 37, 62 | 55 | 50 → 75 → 62 | left child of 62 |
| 50, 25, 75, 87 | 90 | 50 → 75 → 87 | right child of 87 |
| 8, 3, 10, 1, 6, 9, 14 | 7 | 8 → 3 → 6 | right child of 6 |
Operation 3
Delete: three cases
Which delete case applies
L: Leaf
No children to worry about. The parent's pointer becomes
None.O: One child
Lift the only child, with its whole subtree, into the node's place. Everything there was already on the correct side of the parent.
T: Two children
Replace the value with the inorder successor (smallest key in the right subtree), then delete that successor below.
Worked example
Delete in code
Deleting 20, 30 and 50 from 50, 30, 70, 20, 40, 35, 60, 80, 65
- 1
Delete 20: leaf
Path 50 → 30 → 20. No children, so
30.leftbecomesNone. - 2
Delete 30: one child
30 now has only a right child, 40 (with 35 below). That subtree moves up to be 50's left child.
- 3
Delete 50: two children
Right once to 70, left to 60, which has no left child: the successor is 60. Write 60 into the root.
- 4
Remove the old 60
60 has only a right child, 65, so case 2 lifts 65 into its place. Inorder is now 35, 40, 60, 65, 70, 80.
class TreeNode: def __init__(self, val): self.val, self.left, self.right = val, None, Nonedef insert(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) elif val > root.val: root.right = insert(root.right, val) return rootdef delete(root, val): if root is None: return None if val < root.val: root.left = delete(root.left, val) elif val > root.val: root.right = delete(root.right, val) else: if root.left is None: # leaf or only a right child return root.right if root.right is None: # only a left child return root.left succ = root.right # two children while succ.left: succ = succ.left root.val = succ.val root.right = delete(root.right, succ.val) return rootdef inorder(node): return inorder(node.left) + [node.val] + inorder(node.right) if node else []root = Nonefor k in [50, 30, 70, 20, 40, 35, 60, 80, 65]: root = insert(root, k)for k in [20, 30, 50]: root = delete(root, k) print("after deleting", k, inorder(root))print("new root:", root.val) # 60Traversal
Inorder gives sorted order
An inorder traversal visits the left subtree, then the node, then the right subtree. On a BST that is exactly ascending order, in time and stack, with no comparisons at all. Preorder and postorder are the other two depth-first orders, covered in Tree DFS.
Why inorder is sorted
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef kth_smallest(root, k): stack, node = [], root while stack or node: while node: # slide down the left spine stack.append(node) node = node.left node = stack.pop() # next key in sorted order k -= 1 if k == 0: return node.val node = node.rightroot = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(40)), TreeNode(70, TreeNode(60), TreeNode(80)))print([kth_smallest(root, k) for k in range(1, 8)]) # [20, 30, 40, 50, 60, 70, 80]Checking
Validating a BST
Validate with bounds
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef valid_bounds(node, low=float("-inf"), high=float("inf")): if node is None: return True if not (low < node.val < high): return False return valid_bounds(node.left, low, node.val) and valid_bounds(node.right, node.val, high)def valid_inorder(root): prev, stack, node = float("-inf"), [], root while stack or node: while node: stack.append(node) node = node.left node = stack.pop() if node.val <= prev: return False prev, node = node.val, node.right return Truegood = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(40)), TreeNode(70))trap = TreeNode(50, TreeNode(30, TreeNode(20), TreeNode(55)), TreeNode(70))print(valid_bounds(good), valid_bounds(trap), valid_inorder(trap)) # True False FalsePass bounds down
- Each node knows the full range its ancestors allow.
- Catches 55 hiding under 30 in 50's left subtree.
- time, stack.
Compare with children only
- Checks
left < node < rightone level at a time. - Says the trap tree is valid.
- The single most common BST interview bug.
Complexity
Everything costs O(h)
One path per operation
The best case: a balanced tree
The worst case: a chain
| Operation | Balanced | Skewed | Space |
|---|---|---|---|
| Search | iterative, recursive | ||
| Insert | recursive | ||
| Delete (3 cases) | recursive | ||
| Find min / max | |||
| Inorder traversal | |||
| Validate |
Balance
Balanced vs degenerate trees
Insert 10, 20, 30, 40, 50 in sorted order
Balanced (bushy)
- Height about .
- Search, insert, delete in .
- Comes from random or middle-first insertion, or from a self-balancing tree.
Degenerate (skewed)
- Height : a linked list with extra pointers.
- Every operation ; recursion can hit Python's limit.
- Comes from sorted or reverse-sorted insertion.
AVL tree
Keeps the two subtree heights of every node within 1 of each other, using rotations after insert and delete. Strictly balanced, fast lookups.
Red-black tree
Colours nodes red or black and limits the longest path to twice the shortest. Fewer rotations; used by Java's
TreeMapand C++'sstd::map.B-tree
Many keys per node and very shallow. The index structure inside most databases and file systems.
Choosing
BST or hash table?
| Need | Balanced BST | Hash table |
|---|---|---|
| Search / insert / delete | average | |
| Keys in sorted order | inorder | Sort first: |
| Min / max | ||
| Range query [a, b] | ||
| Predecessor / successor | ||
| Space |
Use a BST when you need order
- Sorted iteration, min and max.
- Range queries: every key between and .
- Floor, ceiling, predecessor and successor.
Use a hash table when you only look up
- Only membership, insert and delete.
- No sorted output or range queries needed.
- Then average beats .
Recap
Key takeaways
Key points
- For every node: all left descendants are smaller, all right descendants are larger. Every subtree is a BST.
- Search, insert and delete walk one root-to-leaf path: O(h).
- h is about log₂ n when balanced and n when skewed; sorted insertion builds a chain.
- Insert adds a leaf at the empty slot the search reaches; always keep the returned root.
- Delete: Leaf (remove), One child (lift it), Two children (copy the inorder successor, then delete it).
- Inorder successor: right once, then left all the way. It never has a left child.
- Inorder traversal of a BST is sorted, in O(n).
- Validate with min and max bounds or a strictly increasing inorder, never by checking children only.
- AVL and red-black trees rebalance with rotations to guarantee O(log n).