Skip to main content

6.5 Binary Search Trees (BST): Invariants, Search, Insertion & Deletion

πŸ“šModule 06 β€’ Trees & HierarchiesTopic 6.5⏱️19 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ Core Intuition: The 3-Second Mental Model​

🍳 The Everyday Analogy: The Number-Guessing Eliminator​

Suppose someone secretly picks a number between 11 and 100100:

  • You guess 50 first. If the secret number is smaller, you immediately discard everything β‰₯50\ge 50 (50..100) in one question and step left! If larger, you discard 1..50 and step right.
  • Unlike sorted arrays (where binary search works fast yet inserting a new number forces shifting O(n)\mathcal{O}(n) entries) or linked lists (fast insertion yet O(n)\mathcal{O}(n) 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 XX:

  1. Every key anywhere inside XX's Left Subtree is strictly smaller than X.keyX.\text{key}.
  2. Every key anywhere inside XX's Right Subtree is strictly larger than X.keyX.\text{key}.
  3. Inorder Sorted Theorem: Walking Left -> Root -> Right across any valid BST retrieves all elements in strictly ascending sorted order!

πŸ” 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 / MetricAverage Case (Random Input)Worst Case (Sorted Input Skew)Structural Explanation
Search / Insert / DeleteO(log⁑n)\mathcal{O}(\log n)O(n)\mathcal{O}(n)Sorted arrivals build a straight line of height nβˆ’1n - 1
Find Minimum / MaximumO(log⁑n)\mathcal{O}(\log n)O(n)\mathcal{O}(n)Walk strictly leftmost / rightmost path
Find ANY Non-Max ElementO(1)\mathcal{O}(1)O(1)\mathcal{O}(1)Compare root & child (or just pick smallest of 2 distinct elements!)
Range Report [a, b] (kk hits, balanced)O(log⁑n+k)\mathcal{O}(\log n + k)β€”Locate lower bound a in O(log⁑n)\mathcal{O}(\log n), yield kk sorted keys
Space ComplexityO(n)\mathcal{O}(n)O(n)\mathcal{O}(n)One pointer pair per stored node

Notice that sharp property: finding a key that is not the maximum in a BST of nβ‰₯2n \ge 2 distinct elements takes strictly O(1)\mathcal{O}(1) 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:

πŸ“Why Two-Child Deletion Always Reduces to Case 1 or Case 2theorem

To remove a 2-child node XX:

  1. Locate either its Inorder Predecessor (max in X->left, reached by stepping left once then going rightmost until right == NULL) OR Inorder Successor (min in X->right, reached by going leftmost until left == NULL).
  2. Copy that replacement key into XX, then recursively delete the replacement node.
  3. 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 KK 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: (βˆ’βˆž,+∞)(-\infty, +\infty).
  • Branching Left from probe XX (K<XK < X): updates high = min(high, X) β€” no later probe can exceed XX!
  • Branching Right from probe XX (K>XK > X): updates low = max(low, X) β€” no later probe can fall below XX!

🏭 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​

πŸ“Problem Statementtheorem

Keys between 11 and 10001000 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):

ProbeComparison to Target 363Branch DirectionUpdated Valid Interval (low, high)Valid?
925363<925363 < 925Left(1,925)(1, 925)βœ… Yes
202363>202363 > 202Right(202,925)(202, 925)βœ… Yes
911363<911363 < 911Left(202,911)(202, 911)βœ… Yes
240363>240363 > 240Right(240,911)(240, 911)βœ… Yes
912β€”β€”Violates upper bound 911911!❌ 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​

πŸ“Problem Statementtheorem
  1. Insert keys [71, 65, 84, 69, 67, 83] sequentially into an empty BST and list its Preorder traversal.
  2. Delete the root 71 using its Inorder Predecessor, and verify that the updated Inorder traversal remains strictly sorted.

Step-by-Step Solution:​

  1. Sequential Insertion:
    • Root 71 -> 65 left of 71 -> 84 right of 71 -> 69 right of 65 -> 67 left of 69 -> 83 left of 84.
    • Preorder (N -> L -> R): 71, 65, 69, 67, 84, 83.
    • Inorder (L -> N -> R): 65, 67, 69, 71, 83, 84.
  2. Delete Root 71 via Inorder Predecessor:
    • Left subtree of 71 is [65 -> right: 69 -> left: 67]. Maximum element in that left subtree is 69.
    • Copy 69 into Root (71 -> 69), then delete original node 69 (which has 1 left child 67 β€…β€ŠβŸΉβ€…β€Š\implies Case 2 promotes 67 into 65->right!).
    • Updated Inorder: 65, 67, 69, 83, 84 (Strictly sorted!).

Example 3: Counting BST Insertion Orders Along a Search Path​

πŸ“Problem Statementtheorem

Suppose we insert nn distinct keys into an empty BST and observe that searching for element ee visits nn nodes. How many distinct insertion permutations of those nn visited nodes produce the exact structural path of ksmallk_{\text{small}} elements smaller than ee and klargek_{\text{large}} elements larger than ee visited on the way to ee?

Step-by-Step Solution:​

Among the sequence leading down to ee, all elements smaller than ee MUST preserve their exact relative insertion order (only 11 valid ordering out of ksmall!k_{\text{small}}!), all elements larger than ee MUST preserve their relative insertion order (11 out of klarge!k_{\text{large}}!), and ee itself must arrive lastβ€”meaning any valid interleaving of the smaller and larger chains gives:

ValidΒ Orderings=(ksmall+klarge)!ksmall!Γ—klarge!=(ksmall+klargeksmall)\text{Valid Orderings} = \frac{(k_{\text{small}} + k_{\text{large}})!}{k_{\text{small}}! \times k_{\text{large}}!} = \binom{k_{\text{small}} + k_{\text{large}}}{k_{\text{small}}}

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  • Global vs. Local BST Rule: Checking only node->left->data < node->data and node->right->data > node->data is 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 O(log⁑n)\mathcal{O}(\log n), whereas sorted arrivals give worst-case depth nβˆ’1=O(n)n - 1 = \mathcal{O}(n).
  • BST Range Queries: Reporting all kk keys inside [a, b] on a balanced BST runs in O(log⁑n+k)\mathcal{O}(\log n + k) time by pruning subtrees completely outside [a, b].
Common Interview Traps: Architectural Trade-Offs
  • Local Child Check Validation Bug (20 -> right: 30 -> left: 5): 5 < 30 passes a naive local check on node 30, yet 5 < 20 breaks 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: Assigning root->left = insertBST(...) without returning root (or forgetting to assign root = insertBST(root, key) on initial NULL root) drops the newly created node!
  • Thinking Hash Tables Beat BSTs on Range Queries: Hash tables do O(1)\mathcal{O}(1) point lookups, yet scanning [a, b] requires Θ(n)\Theta(n) full-table scans where a balanced BST finishes in O(log⁑n+k)\mathcal{O}(\log n + k).

πŸš€ 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 O(n)\mathcal{O}(n) skew with AVL self-balancing!

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.