search(30)O(log n) avg
40201030605070
root
active
path
found/inserted
deleted
Search(30): start at root. BST property guides every decision.
start
1 / 7
SPD0.5×
click to pause · hover for controls · fullscreen for more

BST Operations

Search, insert, and delete in O(log n) — with the in-order successor explained

Visual by thisgirltech

IntermediateData Structures

A Binary Search Tree is a tree where every node satisfies one rule: all values in the left subtree are strictly smaller, and all values in the right subtree are strictly larger. This ordering property is what makes search, insert, and delete all run in O(log n) average time on a balanced tree.

At every node you make one binary decision — go left or go right — eliminating the other half of the tree entirely. With n nodes and a balanced tree you need at most log₂(n) comparisons to find anything. That is 20 comparisons for a million nodes, versus a million for a linear scan.

Search — O(log n) avg

Compare the target with the current node. Equal — found. Smaller — go left (all values there are smaller). Larger — go right (all values there are larger). Each comparison eliminates an entire subtree.

Insert — O(log n) avg

Run the same comparison path as search until you reach a null slot. Place the new node there. The BST property is automatically satisfied — no restructuring needed because every comparison guarantees correct placement.

Delete — 3 cases

Leaf: remove directly. One child: bypass the node by connecting parent to child. Two children: find the in-order successor (smallest value in the right subtree), copy its value here, delete the successor — which has at most one child.

Worst case O(n)

Inserting already-sorted values creates a degenerate tree — a linked list. All operations become O(n). Self-balancing variants (AVL, Red-Black) prevent this by rotating after each operation, guaranteeing O(log n) always.

TIP

Watch the DELETE case for node 20 carefully — it has two children (10 and 30), which triggers the in-order successor case. The animation finds 25 (leftmost of the right subtree), copies 25 to node 20's position, then deletes the original 25 node. Step through slowly to see why this preserves BST order.

COLOUR LEGEND

Root node
Currently comparing
Traversal path
Found / inserted
Deleted