Binary Trees & Binary Search Trees Complete Guide

Zaheer Ahmad 4 min read min read
Python
Binary Trees & Binary Search Trees Complete Guide

Introduction

Binary Trees and Binary Search Trees (BSTs) are fundamental data structures in computer science and are widely used in software development, databases, and competitive programming. This binary tree tutorial will guide you step-by-step through the concepts, operations, and real-world applications of binary trees and BSTs.

For Pakistani students studying Data Structures & Algorithms (DSA), mastering these topics is essential. Whether you are preparing for university exams, coding interviews, or platforms like LeetCode and HackerRank, understanding binary search tree operations will significantly improve your problem-solving skills.

Imagine Ahmad managing student records in Lahore or Fatima organizing product prices in an online store in Karachi—efficient data storage and retrieval are crucial. Binary Search Trees provide a fast way to search, insert, and delete data.

Prerequisites

Before starting this guide, you should have:

  • Basic understanding of programming (Python or Java preferred)
  • Knowledge of variables, loops, and functions
  • Familiarity with arrays and linked lists
  • Basic recursion concepts (helpful but not mandatory)

Core Concepts & Explanation

Binary Tree Basics: Structure and Terminology

A binary tree is a hierarchical data structure where each node has at most two children:

  • Root: The top node
  • Left Child: Node on the left
  • Right Child: Node on the right
  • Leaf Node: Node with no children

Example:

        10
       /  \
      5    15
  • 10 → Root
  • 5 → Left child
  • 15 → Right child

Binary trees are used in:

  • Expression evaluation
  • File systems
  • AI decision trees

Binary Search Tree (BST): Rules and Properties

A binary search tree follows a special rule:

Left subtree values < Root < Right subtree values

Example:

        10
       /  \
      5    20
     / \
    2   7
  • All nodes left of 10 are smaller
  • All nodes right of 10 are larger

This property makes searching very fast (O(log n) in balanced cases).

Key BST Operations:

  • Insert
  • Search
  • Delete
  • Traversal (Inorder, Preorder, Postorder)

Practical Code Examples

Example 1: Implementing BST in Python

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BST:
    def insert(self, root, value):
        if root is None:
            return Node(value)
        
        if value < root.value:
            root.left = self.insert(root.left, value)
        else:
            root.right = self.insert(root.right, value)
        
        return root

Line-by-Line Explanation:

  • class Node: → Defines a node structure
  • __init__ → Initializes node with value and empty children
  • class BST: → Defines BST operations
  • insert() → Function to insert a new value
  • if root is None: → Create new node if tree is empty
  • value < root.value → Insert into left subtree
  • else → Insert into right subtree
  • return root → Return updated tree

Example 2: Real-World Application (Student Marks System)

Suppose Ali is building a system to store student marks in Islamabad.

def search(root, key):
    if root is None or root.value == key:
        return root
    
    if key < root.value:
        return search(root.left, key)
    
    return search(root.right, key)

Explanation:

  • search() → Finds a value in BST
  • root is None → Value not found
  • root.value == key → Value found
  • key < root.value → Search left
  • else → Search right

Real-world insight:

  • Fast student lookup system
  • Efficient for large datasets (e.g., thousands of students)

Common Mistakes & How to Avoid Them

Mistake 1: Ignoring BST Property

❌ Wrong approach:
Inserting values randomly without checking order.

✔️ Fix:
Always compare values before inserting.

if value < root.value:
    root.left = insert(root.left, value)

Mistake 2: Forgetting Base Cases in Recursion

❌ Problem:
Infinite recursion or crashes

✔️ Fix:
Always check:

if root is None:
    return Node(value)

Mistake 3: Not Handling Duplicate Values

❌ Problem:
Duplicates may break tree logic

✔️ Fix:
Decide a rule:

  • Ignore duplicates OR
  • Store them consistently (e.g., right subtree)


Practice Exercises

Exercise 1: Inorder Traversal (Sorted Output)

Problem:
Write a function to print BST elements in sorted order.

Solution:

def inorder(root):
    if root:
        inorder(root.left)
        print(root.value)
        inorder(root.right)

Explanation:

  • Traverse left subtree
  • Print root
  • Traverse right subtree

👉 Output will always be sorted in BST.


Exercise 2: Find Minimum Value

Problem:
Find the smallest value in a BST.

Solution:

def find_min(root):
    current = root
    while current.left:
        current = current.left
    return current.value

Explanation:

  • Move left until no node exists
  • Leftmost node = smallest value

Frequently Asked Questions

What is a binary tree?

A binary tree is a hierarchical data structure where each node has at most two children. It is widely used in searching, sorting, and hierarchical data representation.

What is a binary search tree?

A binary search tree is a type of binary tree where left child values are smaller and right child values are larger than the root. This property enables efficient searching.

How do I insert data in a BST?

You compare the value with the root. If smaller, go left; if larger, go right. Repeat until you find the correct position.

Why is BST faster than arrays?

BST allows faster search operations (O(log n)) compared to arrays (O(n)) when the tree is balanced.

How do I traverse a binary tree?

You can use:

  • Inorder (Left, Root, Right)
  • Preorder (Root, Left, Right)
  • Postorder (Left, Right, Root)

Summary & Key Takeaways

  • Binary trees are hierarchical structures with two children per node
  • BST follows the rule: left < root < right
  • BST operations include insert, search, delete, traversal
  • Inorder traversal of BST gives sorted output
  • Recursive thinking is key to mastering trees
  • Used in real-world systems like databases and search engines

To continue your DSA journey on theiqra.edu.pk, explore:

  • Learn how data flows using Stacks & Queues tutorial
  • Dive deeper into connections with Graphs Tutorial
  • Understand memory-efficient structures in Arrays vs Linked Lists
  • Explore problem-solving with Recursion basics

Keep practicing, and soon you'll be solving advanced tree problems like a pro. 🚀

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad