0
0
DSA C++programming~3 mins

Why BST Find Maximum Element in DSA C++?

Choose your learning style9 modes available
The Big Idea

What if you could find the biggest number instantly without looking at every single one?

The Scenario

Imagine you have a messy pile of books with different heights, and you want to find the tallest book. If you try to check each book one by one, it will take a lot of time and effort.

The Problem

Manually searching for the tallest book means looking at every single book, which is slow and tiring. You might lose track or miss some books, making mistakes easy.

The Solution

A Binary Search Tree (BST) organizes books so that taller books are always to the right. To find the tallest book, you just keep moving right until you can't go further. This saves time and effort.

Before vs After
Before
int findMax(int arr[], int size) {
  int max = arr[0];
  for (int i = 1; i < size; i++) {
    if (arr[i] > max) max = arr[i];
  }
  return max;
}
After
int findMax(Node* root) {
  Node* current = root;
  while (current->right != nullptr) {
    current = current->right;
  }
  return current->data;
}
What It Enables

This lets you quickly find the largest value in a sorted structure without checking every item.

Real Life Example

In a phone contact list sorted by name, finding the last contact alphabetically is like finding the maximum in a BST.

Key Takeaways

Manual search checks every item, which is slow.

BST stores data so max is always at the rightmost node.

Finding max in BST is fast and simple by moving right.