Log inStart free
LESSON 3.03 · 6 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Trees and binary search trees

Watch seven keys build a tree, and see why its height sets search cost.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.03 · TREE BAY7 KEYS · 17 COMPARISONS TO BUILD
01
Stage 1 of 6 · Insert keys
Each new node starts at the root. It goes left if smaller and right if larger, to an empty link.
Explain it simply

The keys arrive one at a time, in the order shown at the top left. The first key, 89, becomes the root, the top of the tree. Each later key compares itself with a node and turns left or right, like a hiker at a fork. It stops at the first empty link.

Seven keys go in, in the order 89, 12, 31, 58, 47, 25, 64. The root is 89. The tree has height 4.

node and keylinkempty linksearch path, resultcost, deleted node
insert orderbinary search tree89123158472564insert 64 (key 7 of 7)64 < 89 → left64 > 12 → right64 > 31 → right64 > 58 → right4 comparisonsbuild: 17 in all122256313475584647891insert orderbinary search tree89123158472564insert 64 (key 7 of 7)64 < 89 → left64 > 12 → right64 > 31 → right64 > 58 → right4 comparisonsbuild: 17 in all122256313475584647891
Toy: 7 keys · 1 missing key · 3 insert orders · x position = sorted rank
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
k<n⇒left,k>n⇒right\sy{k}{data}{k} < \sy{n}{param}{n} \Rightarrow \text{left},\qquad \sy{k}{data}{k} > \sy{n}{param}{n} \Rightarrow \text{right}
64<89 ↙, 64>12 ↘, 64>31 ↘, 64>58 ↘ ⇒ 4 comparisons64 < 89\,\swarrow,\ 64 > 12\,\searrow,\ 64 > 31\,\searrow,\ 64 > 58\,\searrow\ \Rightarrow\ \text{4 comparisons}

A smaller key goes left; a larger key goes right.

Common mix-ups

MYTHA BST search always takes about log2 n comparisons.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01If the keys arrive sorted, how many comparisons does a search for the largest key need?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.