Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting
Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting
A Binary Search Tree (BST) is an ordered binary tree that maintains the BST Invariant: $$\text{For every node } X: \quad \text{All nodes in Left Subtree} < X < \text{All nodes in Right Subtree}$$ This ordering property transforms linear searches into fast $O(h)$ tree searches (where $h$ is the height of the tree).
1. Real-World Analogy: The Phonebook or Card Catalog
Think of looking up a contact in an alphabetized address book:
- You open to the middle letter:
'M'. - If you are looking for
'Smith', you know'S' > 'M'. You immediately discard the entire first half of the book! - If you were looking for
'Brown', you would discard the second half. - A BST arranges computer memory so every comparison cuts the candidate search tree in half.
2. The Core BST Operations & Time Complexity
| Operation | Balanced BST Height ($h = \log n$) | Degenerate BST (Skewed $h = n$) |
|---|---|---|
| Search | $O(\log n)$ | $O(n)$ |
| Insert | $O(\log n)$ | $O(n)$ |
| Delete | $O(\log n)$ | $O(n)$ |
Note: If elements are inserted in already sorted order (1, 2, 3, 4, 5), an un-balanced BST degenerates into a singly linked list! Self-balancing trees (AVL, Red-Black Trees) prevent this skewing.
3. Node Deletion Cases in a BST
Deleting a node from a BST has three distinct structural cases:
- 1Case 1: Node is a Leaf (No Children): Simply delete the node (
return None). - 2Case 2: Node has One Child: Splice out the node and replace it with its single child.
- 3Case 3: Node has Two Children (The Classic):
- Find the Inorder Successor (the smallest value in the right subtree:
min_node(root.right)). - Copy the successor's value into the current node.
- Delete the successor node from the right subtree!
4. Multi-Language Implementations: BST Operations
Python 3:
Modern JavaScript / TypeScript:
5. Trace Table: Inserting 25 into BST with Root 50
| Step | Current Node | Comparison | Action |
|---|---|---|---|
| 1 | 50 | $25 < 50$ | Traverse Left to Node 30 |
| 2 | 30 | $25 < 30$ | Traverse Left to Node 20 |
| 3 | 20 | $25 > 20$ | Traverse Right (Right is null) |
| 4 | null | Insert position found | Attach new Node 25 as right child of 20! |
Multiple Choice Questions
node.left.val < node.val && node.right.val > node.val insufficient to validate if a binary tree is a valid BST?Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.