🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Binary Search Tree — Insert, Search, Delete — Complete Beginner Guide

Data Structures FoundationsBinary Search Tree — Insert, Search, Delete🟢 Free Lesson

Binary Search Tree — Insert, Search, Delete — Complete Beginner Guide

Learning Objectives

  • State the binary search tree ordering rule
  • Insert values while keeping order valid
  • Search a tree by discarding half the path
  • Handle the three delete cases
  • Compare average and worst-case tree cost

What Is a Binary Search Tree?

A binary search tree, or BST, is a tree where every node has at most two children. All keys in the left subtree are smaller than the node key. All keys in the right subtree are greater.

That rule turns the tree into sorted structure and enables efficient search.

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


class BST:
    def __init__(self):
        self.root = None

    def insert(self, key):
        self.root = self._insert(self.root, key)

    def _insert(self, node, key):
        if node is None:
            return Node(key)
        if key < node.key:
            node.left = self._insert(node.left, key)
        elif key > node.key:
            node.right = self._insert(node.right, key)
        return node

    def search(self, key):
        node = self.root
        while node is not None:
            if key == node.key:
                return True
            if key < node.key:
                node = node.left
            else:
                node = node.right
        return False


tree = BST()
for value in [50, 30, 70, 20, 40, 60, 80]:
    tree.insert(value)
print(tree.search(40))  # True
print(tree.search(25))  # False

Insert

Start at the root and walk down. If the new key is smaller, go left. If larger, go right. When you hit an empty spot, attach the new node.

StepAction
Empty treeCreate root node
Key smallerRecurse into left child
Key largerRecurse into right child
DuplicateKeep policy such as ignore or count

Average insert is O(log n) when the tree stays balanced.

Search

Search mirrors insert. At each node compare the target and discard one side.

Because you skip an entire subtree each step, a balanced BST behaves like binary search over sorted data.

Tree ShapeSearch Cost
BalancedO(log n)
Skewed like a linked listO(n)

Delete

Delete has three classic cases.

Case One: Leaf Node

Remove the node directly. No children to reattach.

Case Two: One Child

Bypass the node and connect its child to the parent.

Case Three: Two Children

Find the in-order successor, the smallest key in the right subtree. Copy that key into the node, then delete the successor from the right subtree.

python
def delete(node, key):
    if node is None:
        return None
    if key < node.key:
        node.left = delete(node.left, key)
    elif key > node.key:
        node.right = delete(node.right, key)
    else:
        if node.left is None:
            return node.right
        if node.right is None:
            return node.left
        successor = min_node(node.right)
        node.key = successor.key
        node.right = delete(node.right, successor.key)
    return node


def min_node(node):
    current = node
    while current.left is not None:
        current = current.left
    return current

Complexity Snapshot

OperationAverageWorst Case
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
TraversalO(n)O(n)

Sorted input inserted in order creates a straight chain and collapses performance to O(n). Balanced trees fix this in later lessons.

BST versus Hash Table

NeedBSTHash Table
Sorted iterationNaturalNot sorted
Average lookupO(log n)O(1)
Range queriesEfficientAwkward
Guaranteed structureBalanced variantsLoad managed

Drawing BST Shapes

Before coding a new tree operation, draw the shape for a few inserts. Inserting sorted values always grows a right spine, which is the worst case. Interleaving small and large values produces a bushier tree with shorter paths.

Track three values for each node while you draw: key, left child, and right child. For delete with two children, circle the in-order successor so you do not lose the right subtree during the swap.

python
# Sorted inserts create a chain: worst-case O(n) search
def chain_depth(keys):
    depth = 0
    for _ in keys:
        depth += 1
    return depth


print(chain_depth([1, 2, 3, 4, 5]))  # depth equals count

When a plain BST starts failing timing tests, that is your cue to study balanced trees or to switch to a hash table if order does not matter. Recognizing the shape problem early saves hours of micro-optimizing comparisons.

BST Invariants Under Pressure

The BST invariant is easy to state and easy to break. Every node must see all left subtree keys smaller and all right subtree keys larger. One misplaced node can make search skip a valid branch and miss the target.

When debugging a failing insert or delete, print an inorder traversal. On a correct BST the output must be strictly sorted under your duplicate policy. If order breaks, the bug is local to where values crossed.

CheckExpectation
Inorder outputSorted ascending
Height after random insertsNear log n
Height after sorted insertsLinear chain
Delete leafParent pointer updated
Delete two childrenSuccessor copied then removed

Practice writing an is_valid_bst helper that passes min and max bounds down the recursion. That helper becomes a reusable test tool for every later tree assignment.

Key Takeaways

💡

  • BST order rule: left keys smaller, right keys greater
  • Insert and search walk one path from root to leaf
  • Delete uses leaf, one-child, and two-child cases
  • Balanced trees run in O(log n); skewed trees fall to O(n)
  • Sorted insertion order is the worst way to build a plain BST

Practice Questions

  1. Insert 5, 3, 8, 1, 4 in order and sketch the final tree shape.
  2. Explain how search discards half the tree at balanced nodes.
  3. Why does deleting a two-child node require finding an in-order successor?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement