Mr. Tono hangs his gourds by number under the pergola: a real binary search tree from your numbers, search and insert count the gourds compared. What shape…
Why it matters
Search trees sit behind sorted maps and sets, database indexes and autocomplete. Their steps are as many as the tree is high, so its shape decides everything: balanced is O(log n), a chain O(n). That is why AVL and Red-Black trees balance themselves.
The key idea
A tree’s shape is its speed
Common mistakes
The tree becomes a straight chain after inserting already sorted data Every new value lands at the far right: height n, every operation O(n). Use a self-balancing tree (AVL, Red-Black) or shuffle the insert order.
Searching a BST is sometimes fast, sometimes very slow It is only O(log n) when balanced: what decides is the tree’s height and how deep the value sought is, not how many nodes there are.
Unsure how to delete a node with two children without breaking the order Replace it with the in-order successor (the smallest in the right branch): copy its value, then delete that successor, which has at most one child.
Try it in this playground
Search a gourd Count the comparisons: as many as the gourd is deep.
Hang a new gourd It lands right where its search path runs out.
Walk in order Left, me, right: always comes out sorted.
Rebalance a skewed tree The order stays, the height drops.