Overview & Concept
A Binary Search Tree (BST) is a hierarchical node-based data structure where each node has at most two children. It satisfies the binary search invariant: all keys in the left subtree are strictly less than the node key, and all keys in the right subtree are strictly greater. When balanced, BSTs execute search, insertion, and deletion in O(log n) time.
How It Works
BST Invariant: Left child < Current node < Right child for all nodes in the tree.
Binary Elimination: Lookups compare target with current key and discard half the remaining search space.
In-Order Traversal: Visiting left, root, right produces a strictly ascending sorted sequence.
Tree Height Dependency: Search depth is directly proportional to tree height h; balanced trees have h ≈ log₂ n.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(log n) balanced | O(log n) search/insert | O(n) degenerate chain | O(n) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
// Binary Search Tree (BST) Operations operation insert(node, key): if node == null: return new Node(key) if key < node.key: node.left = insert(node.left, key) else if key > node.key: node.right = insert(node.right, key) return node operation search(node, key): if node == null or node.key == key: return node if key < node.key: return search(node.left, key) return search(node.right, key)
- Binary Search Invariant: For any node N: ∀ x ∈ LeftSubtree(N), x.key < N.key, and ∀ y ∈ RightSubtree(N), y.key > N.key.
- Acyclic Invariant: Graph contains no directed cycles, with exactly n-1 edges for n nodes.
Advantages & Disadvantages
Key Advantages
- •O(log n) average time for search, insertion, and deletion.
- •Maintains sorted order: in-order traversal yields sorted elements in O(n) time.
- •Efficient range queries and predecessor/successor lookups.
Trade-offs & Limitations
- •Degenerates to O(n) linked list under sorted or reverse-sorted insertion order.
- •Pointer overhead per node (left, right).
Real-World Applications
In-Memory Sorted Sets & Maps
Underlying std::set, std::map, and TreeMap collections.
Syntax Trees in Compilers
Abstract Syntax Trees (AST) representing code expressions.
Decision Trees in Machine Learning
Classification and regression trees partitioning feature spaces.
Decision Guide: When to Use
Ideal Scenarios
- ✓When you need both fast search and ordered traversal/range queries.
- ✓When data arrives in random order (or when using self-balancing variants like AVL/Red-Black).
Consider Alternatives When
- ✕When inputs arrive pre-sorted without balancing (use AVL Tree).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.