3.4.6 · D3Trees

Worked examples — BST — worst case O(n) — motivation for balancing

2,712 words12 min readBack to topic

Before we start, one reminder of the two symbols we use everywhere:

The cost of search/insert/delete is because each of them walks one path from the root downward — never sideways, never back up. So "how slow is my tree?" is literally "how tall is my tree?"


The scenario matrix

Every BST-height situation you can be handed falls into one of these cells. Our job below is to hit all of them.

Cell Case class What makes it special Example
A Degenerate right stick — sorted increasing insert every key goes right; Ex 1
B Degenerate left stick — sorted decreasing insert every key goes left; Ex 2
C Zig-zag stick — alternating extreme inserts still one node per level; Ex 3
D Perfectly full tree — the best case every level packed; Ex 4
E Degenerate input, empty & single node and edge cases Ex 5
F Mixed / "bushy-ish" — realistic order somewhere in the middle Ex 6
G Real-world word problem — sorted timestamps why "it works on my laptop" fails at scale Ex 7
H Exam twist — count nodes from a height, or invert the bound reading the formula backwards Ex 8
I Limiting behaviour — how big is the gap vs ? the whole reason balancing matters Ex 9

The two "sign/quadrant"-style extremes for a tree are lean-right (Cell A) and lean-left (Cell B); the "zero/degenerate" inputs are Cell E; the "limiting value" is Cell I. That's the whole grid — let's walk it.


Cell A — Degenerate right stick


Cell B — Degenerate left stick


Cell C — Zig-zag stick


Cell D — Perfectly full tree (best case)


Cell E — Empty and single-node (degenerate inputs)


Cell F — Mixed / bushy-ish (realistic middle)


Cell G — Real-world word problem (sorted timestamps)


Cell H — Exam twist (read the formula backwards)


Cell I — Limiting behaviour (the size of the gap)


Active Recall

Which insertion orders both produce ?
Sorted increasing (right stick) and sorted decreasing (left stick) — direction doesn't matter.
Can a non-monotone insertion order still give a degenerate stick?
Yes — a crafted zig-zag order (Cell C) can add one node per level, giving .
A perfectly full tree has height ; how many nodes?
nodes (sum the geometric series, not just the last level).
For , best-case vs worst-case comparison ratio is about?
About (), and it grows to as .
What is for a single-node tree, and why?
, because height counts edges and a lone node has none.

Connections