Web Analytics

๐Ÿ” Binary Search Tree

Intermediate ~30 min read

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

  1. Start at root
  2. If target equals current node โ†’ Found!
  3. If target < current โ†’ Go left
  4. If target > current โ†’ Go right
  5. Repeat until found or reach null

Time: O(log n) average, O(n) worst case

2. Insert

How to Insert

  1. Search for the value (as above)
  2. When you reach null, insert there
  3. 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

Output
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:

  1. BST Property: Left < Root < Right
  2. Search: Compare and go left/right - O(log n)
  3. Insert: Find position and add - O(log n)
  4. Delete: Three cases (leaf, one child, two children)
  5. Inorder: Gives sorted values
  6. 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!