learn/Data Structures/Binary Search Tree
{ } TreeIntermediate interactive

Binary Search Tree

Left < node < right. Ordered O(log n) search.

binary_search_tree
6 nodes · height 3
20
30
40
50
60
70

Left < node < right. Search discards half the tree each step.

How it works

A BST keeps elements ordered: every left descendant is smaller, every right descendant larger. That invariant turns search, insert, and delete into a single root-to-leaf walk — O(log n) when balanced, but O(n) if it degenerates into a line.

Mental models

  • At each node you discard half the tree — that's the log n.
  • In-order traversal (left, node, right) prints values sorted.
  • Self-balancing variants (AVL, Red-Black) guarantee log n height.

Common pitfalls

  • Inserting sorted data builds a linked list — O(n) operations.

Complexity

Search
O(log n)O(n) if unbalanced
Insert
O(log n)
Delete
O(log n)
In-order walk
O(n)yields sorted order
Space
O(n)

Reach for it when

  • Ordered maps / sets
  • Range queries
  • Auto-complete prefixes