Balanced trees and AVL rotations
An AVL tree keeps the heights of each node’s two subtrees within one level of each other. A rotation can restore balance while preserving key order.
Simple example
Insert 3, 2 and 1. The left side grows too tall. Rotate right at 3 and print the new root, 2.
fun main() {
var keys = intArrayOf(3, 2, 1)
var left = intArrayOf(1, 2, -1)
var right = intArrayOf(-1, -1, -1)
var root = 0
var pivot = left[root]
left[root] = right[pivot]
right[pivot] = root
root = pivot
println(keys[root])
}
2
Everyday examples
Rebalance three catalogue cards
Cards 30, 20 and 10 arrive in descending order. Which card should sit at the root after the repair?
Rotate right at 30. Card 20 becomes the root. Searching still visits smaller keys on the left.
Handle ascending ticket numbers
Insert 4, 5 and 6 into an empty AVL ticket index. Which single rotation repairs it?
Rotate left at 4. The new tree keeps both outer tickets one step from 5.
Repair a bent branch
Shelf keys 30, 10 and 20 form a left branch that bends right. Which item ends up in the middle?
Rotate left at 10, then right at 30. Key 20 becomes the root and the sorted order stays 10, 20, 30.
Cost and limits
AVL search, insertion and deletion take logarithmic time. A bend in the heavy branch can require two rotations. A rotation must also reconnect any middle subtree.