Binary Search Tree#
A binary search tree (BST) is a binary tree where for every node: left subtree keys < node key < right subtree keys (or ≤ / ≥ depending on duplicate policy). In-order traversal yields sorted order.
When to use a BST#
| Prefer BST | Prefer hash table |
|---|---|
| Need sorted iteration | Only exact lookup |
| Predecessor / successor | No ordering needed |
| Range queries (with augmentation) | O(1) average lookup suffices |
Interview note: assume balanced BST for O(log n) unless problem creates a skewed tree. Self-balancing variants (AVL, red-black) restore balance after inserts — know they exist; rarely implement from scratch in Python interviews.
Complexity (n nodes, height h)#
| Operation | Balanced h ≈ log n | Skewed h = n |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| In-order traversal | O(n) | O(n) |
| Space | O(n) nodes + O(h) stack | O(n) |
Python: no built-in BST — use bisect on a sorted list, or implement nodes for the interview. Third-party SortedList is uncommon in live coding.
Validate BST (LC 98): each node must satisfy lo < node.val < hi for bounds passed from ancestors — comparing only immediate children is not enough.
Implementation#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |