Rotations and repair — fill in two holes
In the last step you watched seven inserts in a table. Now the same thing is written down as an algorithm — and you fill in two missing pieces.
Pseudocode
The repair happens on the way back up, so insertion becomes recursive:
insert(n, item):
if n = nil: return a new leaf
c.Hit()
if item.Title < n.key: n.left ← insert(n.left, item)
if item.Title > n.key: n.right ← insert(n.right, item)
else: n.item ← item; return n
return rebalance(n) // ← the entire difference from lesson 11
In lesson 11 that last line was return n. Everything else is the same function.
And the four cases you just saw in the table:
rebalance(n):
fix(n) // recompute n's height
b ← balance(n)
if b > 1 and balance(n.left) ≥ 0: // left-left
return rotateRight(n)
if b > 1: // left-right
n.left ← rotateLeft(n.left) // make it left-left
return rotateRight(n)
if b < −1 and balance(n.right) ≤ 0: // right-right
return rotateLeft(n)
if b < −1: // right-left
n.right ← rotateRight(n.right) // make it right-right
return rotateLeft(n)
return n
That is exactly what you did by hand on rows 4 and 6: first turn the child so
that the inner case becomes an outer one, then the parent.
Your job
Create avl.go and avl_test.go (see the panel).
avl.go is complete and compiles, but it does not work. Most of it is
already written: height, balance, fix, rotateRight and the recursive
insert itself — the search part is lesson 11's, in one place. Two places are
missing, marked HOLE 1 and HOLE 2:
- HOLE 1 — the body of
rotateLeft.rotateRightis written right above it; you need two assignments, the same thing mirrored. Which subtree changes parent, and who becomes whose child? - HOLE 2 — the
left-rightcase insiderebalance. Theright-leftcase is written four lines below — this is its mirror. Turn the case intoleft-left, then fall into the rotation that is already written.
Nothing else needs changing.
avl_test.go is the verdict — you do not write it, you pass it. For now it
checks insertion and repair only:
TestTraceReproducesTheLessonTable— the same seven keys, in the same order. After each insert it requires the same comparisons, the same rotations and the same tree shape as the table. If your code "works" but the shape differs, this is where you hear about it.TestEveryInsertKeepsTheInvariant— 300 scrambled keys, and after every insert: stored heights correct,|balance| ≤ 1, keys in order, none lost.
The second uses scrambled keys on purpose. Orderly keys (t00001, t00002,
…) exercise only the two simple rotations; a rebalance with the left-right
case missing would pass the whole suite. Scrambled keys touch all four.
Worth noting
heightmust be nil-safe. An absent subtree has height 0. Half of all AVL bugs are a missing nil check right here, and they show up as "sometimes unbalanced" rather than as a crash. It is already written — look at why it looks the way it does.fixruns on two nodes after a rotation, and the order matters. The one that moved down first, then the one that moved up — the second one's height depends on the first.rotateRightalready does it; yourrotateLeftborrows the same lines.- An equal key does not rebalance.
inserton an existing key only replaces the record and returns early; the shape did not change, so there is nothing to repair. - Rotations are not comparisons.
c.Hit()fires only when two keys are compared. Count rotations there too and step 7 stops working — and step 7 is precisely about what the counter cannot see.
Run the test before you fill anything in
Run it as it stands first:
$ go test ./...
--- FAIL: TestTraceReproducesTheLessonTable (0.00s)
avl_test.go:109: insert 4: cmps / rotations / shape = 3 / 2 / 2(1,4(-,7)), want 3 / 2 / 2(1,4(3,7))
--- FAIL: TestEveryInsertKeepsTheInvariant (0.00s)
avl_test.go:141: balance 2 after 3 inserts, want <= 1
FAIL
That is not an error — it is the starting point. The first message is row 4 of
the table: the comparisons (3) and rotations (2) match, because rotateLeft was
still called and counted — but the shape 2(1,4(-,7)) has lost key 3, because
the rotation moved nothing. The second: by the third insert the tree already has
a node with balance 2 — that needed the left-right case.
Fill in HOLE 1 and run again:
--- FAIL: TestTraceReproducesTheLessonTable (0.00s)
avl_test.go:109: insert 6: cmps / rotations / shape = 3 / 1 / 4(2(1,3),5(-,7(6,-))), want 3 / 2 / 4(2(1,3),6(5,7))
--- FAIL: TestEveryInsertKeepsTheInvariant (0.00s)
avl_test.go:141: balance 2 after 3 inserts, want <= 1
The table moved on: rows up to 5 now pass and it stops at 6 — exactly at
left-right. Fill in HOLE 2 — you should see ok.
When it does not pass
Each of these is a real mistake, tried.
the tree now contains a cycle— the assignments inrotateLeftare in the wrong order, orn.right = r.leftis missing. If you writer.left = nfirst, the oldr.leftis already gone andn.rightreceivesnitself — a node pointing at itself.the tree holds 2 keys (Len 3) — a subtree was lost— a subtree vanished. EitherrotateLeftdid not makena child (r.left = nis missing), or HOLE 2 performed the rotation but did not keep the result.cmps / rotations / shape = …, want …— the shape is wrong. Look at where in the table it stopped:4is HOLE 1,6is HOLE 2.balance 2 after 3 inserts— HOLE 2 is still empty, or you rotated the wrong way in it.nil pointer dereferencefromrotateRight— HOLE 2 rotatedn.leftto the right. The inner child leans right, so it has to be rotated left;rotateRightfound no node there to lift.
rebalance returns the new subtree root, and the caller has to take that
value:
n.left = t.insert(n.left, it, c) // correct — the subtree may have a new root
t.insert(n.left, it, c) // wrong — a rotation happened and was thrown away
The second version compiles and reports no error. Len() climbs on every call,
because the counter is incremented where the leaf is created — but the leaf
itself is thrown away. Measured:
--- FAIL: TestEveryInsertKeepsTheInvariant (0.00s)
avl_test.go:129: after 2 inserts the tree holds 1 keys (Len 2) — a subtree was lost
A silent no-op that still increments the count is a nastier failure than a
crash. That is why the test counts, after every insert, how many keys are
really in the tree, and compares that with Len().