6.5 Binary Search Trees (BST): Invariants, Search, Insertion & Deletion
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: The Number-Guessing Eliminatorβ
Suppose someone secretly picks a number between and :
- You guess
50first. If the secret number is smaller, you immediately discard everything (50..100) in one question and step left! If larger, you discard1..50and step right. - Unlike sorted arrays (where binary search works fast yet inserting a new number forces shifting entries) or linked lists (fast insertion yet sequential scan), a Binary Search Tree runs binary search across dynamic heap pointers!
π» Bridging to Computer Science: The Global BST Ordering Lawβ
A Binary Search Tree (BST) (also called an Ordered / Sorted Binary Tree) enforces one recursive rule at every single node :
- Every key anywhere inside 's Left Subtree is strictly smaller than .
- Every key anywhere inside 's Right Subtree is strictly larger than .
- Inorder Sorted Theorem: Walking
Left -> Root -> Rightacross any valid BST retrieves all elements in strictly ascending sorted order!
πTable of Contents
- π Search, Insertion & Skewed Worst-Case Pathology
- βοΈ Deletion in a BST: The 3 Canonical Cases
- π― Valid Search Probe Sequence Invariant
- π Real-World Production Context: Indexes, Ordered Maps & Range Scans
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π Search, Insertion & Skewed Worst-Case Pathologyβ
Searching descends one child pointer per comparison until matching key or hitting NULL; insertion descends the identical search path and attaches the new key as a new terminal leaf node:
// O(h) Search in BST (Avg: O(log n), Worst-case skewed: O(n))
struct TreeNode* searchBST(struct TreeNode *root, int key) {
if (root == NULL || root->data == key) return root;
return (key < root->data)
? searchBST(root->left, key)
: searchBST(root->right, key);
}
// O(h) Leaf Insertion in BST
struct TreeNode* insertBST(struct TreeNode *root, int key) {
if (root == NULL) return createNode(key);
if (key < root->data) root->left = insertBST(root->left, key);
else if (key > root->data) root->right = insertBST(root->right, key);
return root;
}
Fast Bounds & Why Unbalanced BSTs Degrade to Linear Timeβ
| Operation / Metric | Average Case (Random Input) | Worst Case (Sorted Input Skew) | Structural Explanation |
|---|---|---|---|
| Search / Insert / Delete | Sorted arrivals build a straight line of height | ||
| Find Minimum / Maximum | Walk strictly leftmost / rightmost path | ||
| Find ANY Non-Max Element | Compare root & child (or just pick smallest of 2 distinct elements!) | ||
Range Report [a, b] ( hits, balanced) | β | Locate lower bound a in , yield sorted keys | |
| Space Complexity | One pointer pair per stored node |
Notice that sharp property: finding a key that is not the maximum in a BST of distinct elements takes strictly timeβinspecting just the root and one neighbor instantly reveals a non-maximum value! Conversely, feeding sorted keys (10, 20, 30, ...) forms a skewed linked list, motivating AVL self-balancing rotations (Topic 6.7).
βοΈ Deletion in a BST: The 3 Canonical Casesβ
Deleting an existing key must unlink the node while keeping Inorder strictly sorted. Deletion splits cleanly into three cases based on child count:
To remove a 2-child node :
- Locate either its Inorder Predecessor (
maxinX->left, reached by stepping left once then going rightmost untilright == NULL) OR Inorder Successor (mininX->right, reached by going leftmost untilleft == NULL). - Copy that replacement key into , then recursively delete the replacement node.
- Because the Inorder Predecessor has zero right children (and Inorder Successor has zero left children), the replacement node ALWAYS has at most 1 child!
struct TreeNode* findMin(struct TreeNode *node) {
while (node->left != NULL) node = node->left;
return node;
}
struct TreeNode* deleteBST(struct TreeNode *root, int key) {
if (root == NULL) return NULL;
if (key < root->data) root->left = deleteBST(root->left, key);
else if (key > root->data) root->right = deleteBST(root->right, key);
else {
if (root->left == NULL) { // Case 1 & Case 2 (0 or right child)
struct TreeNode *tmp = root->right;
free(root);
return tmp;
} else if (root->right == NULL) { // Case 2 (left child only)
struct TreeNode *tmp = root->left;
free(root);
return tmp;
}
struct TreeNode *succ = findMin(root->right); // Case 3: Inorder Successor
root->data = succ->data;
root->right = deleteBST(root->right, succ->data);
}
return root;
}
π― Valid Search Probe Sequence Invariantβ
When searching for a target inside a valid BST, every branching decision permanently shrinks the allowable (low, high) key interval for all future nodes along that search path:
- Starting interval: .
- Branching Left from probe (): updates
high = min(high, X)β no later probe can exceed ! - Branching Right from probe (): updates
low = max(low, X)β no later probe can fall below !
π Real-World Production Context: Indexes, Ordered Maps & Range Scansβ
BST Architectures in Production Systems
Ordered lookup engines powering databases, standard libraries, and kernel schedulers
C++ std::map / std::set
Ordered Containers- Maintains keys inside self-balancing Binary Search Trees for O(log n) lookup, predecessor/successor lower_bound(), and sorted iteration.
- Zero hash collisions even under adversarial key distributions.
Sorted Range Reporting
Time-Series & Leaderboards- Answers queries like 'find all records in [a, b]' in optimal O(log n + k) time.
- Hash tables fail here because hashing destroys relative numerical key proximity.
OS Virtual Memory Area (VMA) Trees
Linux mm_struct- Tracks sorted non-overlapping process memory segments dynamically mapped by mmap() and page-fault handlers.
- Finds enclosing [vm_start, vm_end] interval in O(log n) microseconds.
Dynamic Symbol Tables
Interpreters & Scopes- Supports alphabetical listing, autocomplete prefix bounds, and dynamic insertions efficiently.
- Optimal BST construction via dynamic programming minimizes weighted lookup cost for static keyword sets.
π Numerical Applications & Worked Examplesβ
Example 1: Validating BST Search Probe Intervalsβ
Keys between and reside inside a valid BST, and a search looks for target 363. Test whether the probe sequence [925, 202, 911, 240, 912, 245, 363] is valid or impossible, proving the exact step where any invariant breaks.
Step-by-Step Solution:β
Maintain running valid bounds (low, high), initialized to (1, 1000):
| Probe | Comparison to Target 363 | Branch Direction | Updated Valid Interval (low, high) | Valid? |
|---|---|---|---|---|
925 | Left | β Yes | ||
202 | Right | β Yes | ||
911 | Left | β Yes | ||
240 | Right | β Yes | ||
912 | β | β | Violates upper bound ! | β IMPOSSIBLE! |
Because branching Left from 911 confined the remaining subtree strictly to < 911, encountering 912 later is mathematically impossible in any BST!
Example 2: Tracing Consecutive Insertion & Root Deletionβ
- Insert keys
[71, 65, 84, 69, 67, 83]sequentially into an empty BST and list its Preorder traversal. - Delete the root
71using its Inorder Predecessor, and verify that the updated Inorder traversal remains strictly sorted.
Step-by-Step Solution:β
- Sequential Insertion:
- Root
71->65left of71->84right of71->69right of65->67left of69->83left of84. - Preorder (
N -> L -> R):71, 65, 69, 67, 84, 83. - Inorder (
L -> N -> R):65, 67, 69, 71, 83, 84.
- Root
- Delete Root
71via Inorder Predecessor:- Left subtree of
71is[65 -> right: 69 -> left: 67]. Maximum element in that left subtree is69. - Copy
69into Root (71 -> 69), then delete original node69(which has 1 left child67Case 2 promotes67into65->right!). - Updated Inorder:
65, 67, 69, 83, 84(Strictly sorted!).
- Left subtree of
Example 3: Counting BST Insertion Orders Along a Search Pathβ
Suppose we insert distinct keys into an empty BST and observe that searching for element visits nodes. How many distinct insertion permutations of those visited nodes produce the exact structural path of elements smaller than and elements larger than visited on the way to ?
Step-by-Step Solution:β
Among the sequence leading down to , all elements smaller than MUST preserve their exact relative insertion order (only valid ordering out of ), all elements larger than MUST preserve their relative insertion order ( out of ), and itself must arrive lastβmeaning any valid interleaving of the smaller and larger chains gives:
π― Exam & Interview Pitfall Checkβ
- Global vs. Local BST Rule: Checking only
node->left->data < node->dataandnode->right->data > node->datais insufficient! Every descendant anywhere in the right subtree must exceed all ancestors along whose right branch it lies. - Inorder Predecessor vs. Successor Choice: Both preserve sorted BST order on 2-child deletion; neither choice is forced unless a balanced tree or spec mandates one consistently.
- Average Depth vs. Worst-Case Depth: Expected depth of a randomly inserted BST is , whereas sorted arrivals give worst-case depth .
- BST Range Queries: Reporting all keys inside
[a, b]on a balanced BST runs in time by pruning subtrees completely outside[a, b].
- Local Child Check Validation Bug (
20 -> right: 30 -> left: 5):5 < 30passes a naive local check on node30, yet5 < 20breaks the global BST property! Always pass(minBound, maxBound)recursively down validation calls. - Assuming Both Deletion Children Are Equal: Never unlink a 2-child node directly into its parent without Predecessor/Successor promotionβdoing so leaves three subtrees competing for one pointer slot!
- Forgetting
return root;in Recursive C Insert/Delete: Assigningroot->left = insertBST(...)without returningroot(or forgetting to assignroot = insertBST(root, key)on initialNULLroot) drops the newly created node! - Thinking Hash Tables Beat BSTs on Range Queries: Hash tables do point lookups, yet scanning
[a, b]requires full-table scans where a balanced BST finishes in .
π Navigation & Next Stepsβ
First, let's see how unused NULL pointers inside BSTs/Binary Trees can eliminate traversal recursion stacks completely in Topic 6.6 β Threaded Binary Trees & Inorder Threading, before eliminating skew with AVL self-balancing!
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.