Binary Search Tree
A binary tree where each node has at most two children, and for every node, all values in the left subtree are less than the node’s value, and all values in the right subtree are greater.Overview
Binary Search Trees (BST) provide O(log n) average-case performance for search, insertion, and deletion operations. The BST property enables efficient searching by eliminating half of the remaining nodes at each step.Implementation
Node Structure
Class Definition
BST Property
BST Invariant: For any node N:
- All values in the left subtree < N.value
- All values in the right subtree > N.value
- Both left and right subtrees are also BSTs
API Reference
insert(key: T): boolean
Inserts a new value into the tree while maintaining BST property.- Average: O(log n)
- Worst (skewed tree): O(n)
search(key: T): boolean
Searches for a value in the tree.- Average: O(log n)
- Worst (skewed tree): O(n)
min(): T | undefined
Finds the minimum value in the tree (leftmost node).max(): T | undefined
Finds the maximum value in the tree (rightmost node).remove(key: T): boolean
Removes a node from the tree while maintaining BST property.- Leaf node: Simply remove
- One child: Replace with child
- Two children: Replace with in-order successor (minimum of right subtree)
- Average: O(log n)
- Worst (skewed tree): O(n)
Traversal Methods
In-Order Traversal
Visits nodes in ascending order: left → node → rightPre-Order Traversal
Visits nodes: node → left → rightPost-Order Traversal
Visits nodes: left → right → nodeComplexity Summary
| Operation | Average | Worst Case | Best Case |
|---|---|---|---|
| insert | O(log n) | O(n) | O(1) |
| search | O(log n) | O(n) | O(1) |
| remove | O(log n) | O(n) | O(1) |
| min/max | O(log n) | O(n) | O(1) |
| traversal | O(n) | O(n) | O(n) |
Common Patterns
Validate BST
Find Closest Value
Find Kth Smallest
Range Query
Use Cases
BSTs are ideal for:
- Maintaining sorted data with frequent insertions/deletions
- Range queries (find all values between x and y)
- Finding kth smallest/largest element
- Auto-complete and spell checkers
- Priority queues (when balanced)
Balanced vs Unbalanced
Balanced BST
Unbalanced (Skewed) BST
Key Characteristics
Advantages:
- Average O(log n) search, insert, delete
- Maintains sorted order
- Efficient range queries
- In-order traversal gives sorted sequence
- Simple to implement
Related Data Structures
AVL Tree
Self-balancing BST with guaranteed O(log n)
Binary Heap
Different ordering for priority queues
Tree
General tree without ordering constraint