Data structures

Binary Search Tree

Build a binary search tree one value at a time. See why the shape depends on insertion order, and how search, in-order traversal, and degeneration work.

7 minLevel 2/3The interactive stage stays ad-free.
Nodes9Height4BalanceBalancedBest height4
203540306560807050
In-order20 · 30 · 35 · 40 · 50 · 60 · 65 · 70 · 80

Insert a value to grow the tree.

Insert values in different orders, then use Search to highlight the comparison path. Sorted input such as 10, 20, 30, 40 turns the tree into a linked list, so the balance panel reports Skewed and the height approaches the node count. Balanced insertion keeps the height near log₂ n.

What you are seeing

1

Every node has at most two children. Left descendants are smaller; right descendants are larger.

2

Insertion walks down from the root and attaches the new value at the first empty spot.

3

In-order traversal visits left subtree, node, then right subtree, producing sorted output.

Why it matters

Binary search trees are the foundation of ordered maps, databases, and many interview questions. They also show why balanced trees exist: a bad insertion order can turn O(log n) into O(n).

Complexity & details

Average search/insert: O(log n). Worst case (skewed tree): O(n). Space: O(n).

Frequently asked questions

Why does insertion order matter?+

A balanced tree keeps height near log n. Inserting sorted values into a plain BST creates a linked list, so operations become linear.

How do balanced trees fix this?+

AVL and red-black trees rotate nodes after insertions and deletions to keep the height logarithmic.