0
0
DSA Goprogramming~3 mins

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

Choose your learning style9 modes available
The Big Idea

Discover how a simple order in a tree can save you hours of searching!

The Scenario

Imagine you have a big family tree drawn on paper with no order. You want to find a cousin, but you have to check every name one by one.

The Problem

Searching for someone in this unordered tree is slow and tiring because you might look at every single person before finding the right one or giving up.

The Solution

A Binary Search Tree (BST) keeps the tree organized so you can quickly decide to go left or right, cutting down the search time drastically.

Before vs After
Before
func SearchInBinaryTree(root *Node, target int) bool {
    if root == nil {
        return false
    }
    if root.value == target {
        return true
    }
    return SearchInBinaryTree(root.left, target) || SearchInBinaryTree(root.right, target)
}
After
func SearchInBST(root *Node, target int) bool {
    if root == nil {
        return false
    }
    if root.value == target {
        return true
    } else if target < root.value {
        return SearchInBST(root.left, target)
    } else {
        return SearchInBST(root.right, target)
    }
}
What It Enables

BSTs enable fast searching, inserting, and deleting, making large data easy to manage and access quickly.

Real Life Example

Think of a phone book sorted by names. You can quickly find a contact by jumping to the right section instead of flipping every page.

Key Takeaways

Plain binary trees have no order, making search slow.

BSTs keep data sorted to speed up search and updates.

Using BSTs saves time and effort in managing data.