function insert(node: Node | null, key: number): Node { if (node === null) return { key, left: null, right: null, height: 1 };if (key < node.key) node.left = insert(node.left, key);
else node.right = insert(node.right, key);
node.height = 1 + Math.max(height(node.left), height(node.right));
const balance = height(node.left) - height(node.right);
if (balance > 1 && key < node.left!.key) return rotateRight(node);
if (balance < -1 && key > node.right!.key) return rotateLeft(node);
if (balance > 1) { node.left = rotateLeft(node.left!); return rotateRight(node); } if (balance < -1) { node.right = rotateRight(node.right!); return rotateLeft(node); }return node;
}
function rotateRight(node: Node): Node {const pivot = node.left!;
node.left = pivot.right;
pivot.right = node;
update(node); update(pivot);
return pivot;
}
The tree is empty: 24 becomes the root.
Understanding AVL tree
The idea
An AVL tree is a binary search tree that stores the height of every node and keeps the balance factor, left height minus right height, within −1, 0 or +1. Insertion walks down like a plain BST, then on the way back up recomputes heights; the first node whose balance reaches ±2 is rebalanced by a rotation.
There are four cases. Left-left and right-right take a single rotation: the heavy child comes up and the node drops to the other side. Left-right and right-left first rotate the child to turn the case into a single one, then rotate the node. The label under each node is its balance factor.
The four stages
Complexity
Versus its siblings
Pseudocode
INSERT(node, key)
insert as in a BST, then on the way back up:
height(node) ← 1 + max(height(left), height(right)); balance ← height(left) − height(right)
if balance = +2 and the key went left-left: ROTATERIGHT(node)
if balance = −2 and the key went right-right: ROTATELEFT(node)
if balance = +2 (left-right): left ← ROTATELEFT(left); ROTATERIGHT(node)
if balance = −2 (right-left): right ← ROTATERIGHT(right); ROTATELEFT(node)
When to use
Pitfalls
History
Georgy Adelson-Velsky and Evgenii Landis published the tree in 1962; it was the first self-balancing search tree and takes its name from their initials. Knuth called it one of the most elegant data structures known, and it remains the reference against which red-black trees and B-trees are compared.