๐ Binary Search Tree
Imagine a library where books are organized: smaller numbers on the left shelves, larger numbers on the right. To find a book, you compare and go left or right - much faster than checking every shelf! This is exactly how a Binary Search Tree (BST) works.
The Problem with Regular Trees
In a regular binary tree, finding a value requires checking every node - O(n) time. But what if we could organize the tree so we can eliminate half the remaining nodes with each comparison?
The BST Solution
Add one simple rule: Left < Root < Right
This single property enables O(log n) search in balanced trees!
The BST Property
For every node in a BST:
The Golden Rule
- All values in the left subtree are smaller
- All values in the right subtree are larger
- This applies to every node in the tree
See the Property
Why BST is Powerful
The Magic of Ordering
Inorder traversal gives sorted values!
Example: Tree with [50, 30, 70, 20, 40, 60, 80]
Inorder: [20, 30, 40, 50, 60, 70, 80] โ Sorted!
Basic Operations
1. Search
How to Search
- Start at root
- If target equals current node โ Found!
- If target < current โ Go left
- If target > current โ Go right
- Repeat until found or reach null
Time: O(log n) average, O(n) worst case
2. Insert
How to Insert
- Search for the value (as above)
- When you reach null, insert there
- BST property is automatically maintained!
Time: O(log n) average, O(n) worst case
3. Delete
Three Cases
Case 1: Leaf node - Simply remove it
Case 2: One child - Replace with that child
Case 3: Two children - Replace with inorder successor (min in right subtree)
Time: O(log n) average, O(n) worst case
The Complete Code
Click Run to execute your code
Balanced vs Skewed Trees
Performance Depends on Balance
Balanced tree: Height = O(log n) โ Operations are O(log n)
Skewed tree: Height = O(n) โ Operations degrade to O(n)
Solution: Self-balancing trees (AVL, Red-Black) maintain O(log n)
Real-World Applications
Where BSTs Are Used
- Databases: Index structures for fast queries
- File Systems: Directory organization
- Compilers: Symbol tables
- Autocomplete: Dictionary implementations
- Priority Queues: Efficient min/max operations
Summary
What You've Learned
Binary Search Trees enable efficient searching through ordering:
- BST Property: Left < Root < Right
- Search: Compare and go left/right - O(log n)
- Insert: Find position and add - O(log n)
- Delete: Three cases (leaf, one child, two children)
- Inorder: Gives sorted values
- Balance matters: Skewed trees degrade to O(n)
What's Next?
You've mastered BST fundamentals! The Trees module is complete. Next, we'll explore more advanced data structures and algorithms!
Enjoying these tutorials?