Binary Search Tree
A rooted binary tree where each node's left subtree has smaller keys and right subtree has larger keys.
The Mathematics
BST property, insertion and search, and height analysis
BST Property
For every node in a Binary Search Tree:
This invariant enables efficient search by eliminating half the remaining tree at each comparison.
Search
To search for key , compare with the current node and recurse:
If : found
If : search left subtree
If : search right subtree
Insertion
Insertion follows the same path as search. When we reach a pointer, we create a new leaf node:
Height Analysis
All operations take time, where is the tree height:
Best case (balanced):
Worst case (degenerate): (inserting sorted data creates a linked list)
Self-balancing trees (AVL, Red-Black) guarantee after every operation, ensuring worst-case performance.
See It Work
Building a BST by inserting [5, 3, 7, 1, 4, 6, 8]
Empty tree. Insert 5 as the root node.
The Code
Mapping BST operations to recursive Python functions
Mathematical Formulation
Base case: empty subtree — create a new leaf node
BST property: smaller keys go in the left subtree
BST property: larger keys go in the right subtree
Search: if current node matches, return it
Operations take O(height) time — O(log n) when balanced
Python Implementation
class Node:
def __init__(self, key):
self.key = key
self.left = self.right = None
def insert(root, key):
if root is None:
return Node(key) # Create leaf
if key < root.key:
root.left = insert(root.left, key) # Go left
else:
root.right = insert(root.right, key) # Go right
return root
def search(root, key):
if root is None or root.key == key:
return root # Found or miss
if key < root.key:
return search(root.left, key) # Search left
return search(root.right, key) # Search right