Binary Search Tree
Binary Search Tree
A Binary Search Tree (BST) is a hierarchical data structure where each node has at most two children, and for every node: all values in its left subtree are smaller, and all values in its right subtree are larger. This ordering property enables efficient searching, insertion, and deletion in O(log n) average time — similar to binary search on a sorted array, but with the flexibility to insert and delete without shifting elements.
The BST Property
For every node with value v:
- All nodes in the left subtree have values < v
- All nodes in the right subtree have values > v
This invariant holds recursively for every subtree in the tree.
Core Operations
| Operation | Average | Worst (unbalanced) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
| Min/Max | O(log n) | O(n) |
| In-order traversal | O(n) | O(n) |
How It Works
Search
- Start at the root
- If the target equals the current node, return it
- If the target is less, go left
- If the target is greater, go right
- If you reach a null node, the target doesn't exist
Insertion
- Search for where the value should go
- When you reach a null position, create a new node there
Deletion
Three cases:
- Leaf node: Simply remove it
- One child: Replace the node with its child
- Two children: Find the in-order successor (smallest in right subtree), copy its value, then delete the successor
Step-by-Step Example
Insert [8, 3, 10, 1, 6, 14, 4, 7]:
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7
Search for 6: 8 → left → 3 → right → 6 ✓ (3 comparisons) Search for 5: 8 → left → 3 → right → 6 → left → 4 → right → null ✗ (not found)
Code Snippet
class TreeNode:
"""A single node in the binary search tree."""
def __init__(self, value: int):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
"""Binary Search Tree with search, insert, and delete operations."""
def __init__(self):
self.root = None
def insert(self, value: int) -> None:
"""Insert a value into the BST."""
self.root = self._insert_recursive(self.root, value)
def _insert_recursive(self, node, value: int):
if node is None:
return TreeNode(value)
if value < node.value:
node.left = self._insert_recursive(node.left, value)
elif value > node.value:
node.right = self._insert_recursive(node.right, value)
return node
def search(self, value: int) -> bool:
"""Check if a value exists in the BST."""
current = self.root
while current is not None:
if value == current.value:
return True
elif value < current.value:
current = current.left
else:
current = current.right
return False
def delete(self, value: int) -> None:
"""Remove a value from the BST."""
self.root = self._delete_recursive(self.root, value)
def _delete_recursive(self, node, value: int):
if node is None:
return None
if value < node.value:
node.left = self._delete_recursive(node.left, value)
elif value > node.value:
node.right = self._delete_recursive(node.right, value)
else:
# Node found — handle three cases
if node.left is None:
return node.right
if node.right is None:
return node.left
# Two children: find in-order successor
successor = self._find_min(node.right)
node.value = successor.value
node.right = self._delete_recursive(node.right, successor.value)
return node
def _find_min(self, node):
"""Find the node with the minimum value in a subtree."""
current = node
while current.left is not None:
current = current.left
return current
def inorder_traversal(self) -> list[int]:
"""Return all values in sorted order."""
result = []
self._inorder(self.root, result)
return result
def _inorder(self, node, result: list) -> None:
if node is not None:
self._inorder(node.left, result)
result.append(node.value)
self._inorder(node.right, result)
Complexity Analysis
Time Complexity: O(log n) average, O(n) worst case
- In a balanced BST, the height is O(log n), so search/insert/delete traverse at most log n levels.
- In the worst case (e.g., inserting sorted data: 1, 2, 3, 4, 5), the tree degenerates into a linked list with height n.
Space Complexity: O(n)
The tree stores n nodes, each with a value and two pointers. Recursive operations use O(h) stack space where h is the height.
Balanced vs. Unbalanced
| Input | Tree shape | Height | Operations |
|---|---|---|---|
| Random | Roughly balanced | O(log n) | O(log n) |
| Sorted | Linked list | O(n) | O(n) |
| Alternating | Nearly balanced | O(log n) | O(log n) |
To guarantee O(log n) performance, use self-balancing variants:
- AVL Tree: Strict balance (height difference ≤ 1)
- Red-Black Tree: Relaxed balance (used in most standard libraries)
- B-Tree: Used in databases and filesystems
Traversal Orders
| Order | Sequence | Use case |
|---|---|---|
| In-order | Left → Root → Right | Sorted output |
| Pre-order | Root → Left → Right | Copy/serialize tree |
| Post-order | Left → Right → Root | Delete tree, evaluate expressions |
| Level-order | BFS by level | Print tree layer by layer |
When to Use BSTs
- Dynamic sorted data: Need to insert, delete, and search while maintaining order.
- Range queries: Find all elements between two values efficiently.
- Ordered iteration: In-order traversal gives sorted output.
- Floor/Ceiling queries: Find the largest value ≤ x or smallest value ≥ x.
- Symbol tables with ordering: When you need both fast lookup and sorted access.
When to Avoid BSTs
- Unordered lookups only: Hash maps are faster (O(1) vs O(log n)) if you don't need ordering.
- Static data: A sorted array with binary search is simpler and uses less memory.
- Guaranteed worst-case: Use a self-balancing variant rather than a plain BST.
Key Properties
| Property | Value |
|---|---|
| Average search | O(log n) |
| Worst-case search | O(n) |
| Ordered | Yes (in-order traversal) |
| Dynamic | Yes (efficient insert/delete) |
| Balanced guarantee | No (use AVL/Red-Black for this) |