0
0
DSA C++programming~3 mins

Why BST Over Plain Binary Tree in DSA C++ - The Real Reason

Choose your learning style9 modes available
The Big Idea

Discover how a simple order can turn a slow search into a lightning-fast find!

The Scenario

Imagine you have a big family photo album with hundreds of pictures scattered randomly on shelves. When you want to find a photo of your cousin, you have to look through every single picture one by one.

The Problem

Searching through all photos manually takes a lot of time and effort. You might miss the photo or get tired quickly. This slow and messy process makes finding what you want frustrating.

The Solution

A Binary Search Tree (BST) organizes photos by name in order, so you can quickly jump to the right shelf and find your cousin's photo without checking every picture. This saves time and effort.

Before vs After
Before
void searchNode(Node* root, int value) {
  if (!root) return;
  searchNode(root->left, value);
  if (root->data == value) {
    std::cout << "Found" << std::endl;
  }
  searchNode(root->right, value);
}
After
bool searchBST(Node* root, int value) {
  if (!root) return false;
  if (root->data == value) return true;
  if (value < root->data) return searchBST(root->left, value);
  else return searchBST(root->right, value);
}
What It Enables

BSTs enable fast searching, inserting, and deleting by keeping data in a sorted order.

Real Life Example

Phone contact lists use BST-like structures to quickly find a contact by name instead of scrolling through every contact.

Key Takeaways

Plain binary trees store data without order, making search slow.

BSTs keep data sorted, allowing quick search and updates.

Using BSTs improves efficiency in many applications like databases and contact lists.