Binary Search Tree
A Binary Search Tree (BST) is a binary tree with one extra rule that makes it incredibly useful: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger.
Think of it like a well-organized library catalog. At every junction you get a simple question: "Is what you're looking for smaller or bigger than this?" That one rule lets you cut your search space in half at every step.
The BST property
This must hold for every node in the tree, not just the root. It's a recursive guarantee.
← → arrow keys to step · click elements to interact
BST Insert, Search & In-order
Searching in a BST
Search starts at the root and asks one question per node: "Is the target smaller, bigger, or equal to the current node?"
- Equal — found it!
- Smaller — go left
- Bigger — go right
- Reached null — not in the tree
Each comparison eliminates roughly half the remaining nodes. In a balanced tree this gives \(O(\log n)\) time — like binary search on a sorted array, but in tree form.
Inserting into a BST
Insertion follows the same path as search. You walk down the tree using the same left/right rule until you find an empty slot, then place the new node there. The BST property is automatically preserved.
Deleting from a BST
Deletion has three cases depending on how many children the target node has:
- No children (leaf) — just remove it.
- One child — replace the node with its child.
- Two children — find the in-order successor (smallest value in the right subtree), copy its value here, then delete the successor from the right subtree.
In-order gives sorted output
One of the most powerful properties of a BST: an in-order traversal (Left → Root → Right) always produces the values in ascending sorted order. A BST with values {5, 3, 8, 1, 4} visited in-order gives 1, 3, 4, 5, 8 — perfectly sorted!
Complexity
When does a BST degrade?
If you insert values in sorted order (1, 2, 3, 4, 5...) every new node goes to the right child of the previous one. The tree becomes a straight line — effectively a linked list. All operations now cost \(O(n)\) instead of \(O(\log n)\).
This is why balanced BSTs (like AVL trees and Red-Black trees) exist — they automatically restructure themselves to prevent this degradation.
Use cases
- Maintaining a sorted collection with frequent insertions and deletions
- Range queries (find all values between X and Y)
- In-order iteration over sorted data
- As the basis for AVL trees, Red-Black trees, and treaps
BST Delete (3 Cases)
Quick check
Continue reading