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.
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.
| Step | Action |
|---|---|
| Empty tree | Create root node |
| Key smaller | Recurse into left child |
| Key larger | Recurse into right child |
| Duplicate | Keep 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 Shape | Search Cost |
|---|---|
| Balanced | O(log n) |
| Skewed like a linked list | O(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.
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
| Operation | Average | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Traversal | O(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
| Need | BST | Hash Table |
|---|---|---|
| Sorted iteration | Natural | Not sorted |
| Average lookup | O(log n) | O(1) |
| Range queries | Efficient | Awkward |
| Guaranteed structure | Balanced variants | Load 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.
# 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.
| Check | Expectation |
|---|---|
| Inorder output | Sorted ascending |
| Height after random inserts | Near log n |
| Height after sorted inserts | Linear chain |
| Delete leaf | Parent pointer updated |
| Delete two children | Successor 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
- Insert 5, 3, 8, 1, 4 in order and sketch the final tree shape.
- Explain how search discards half the tree at balanced nodes.
- 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
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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