AVL trees

A tree that straightens itself Β· Part of Trees and graphs

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

AVL tree

A binary search tree can lean after many insertions and deletions, going from O(log n) to O(n). In 1962, Adelson-Velsky and Landis invented the AVL tree, which carries their initials: a search tree that, after each insertion or deletion, checks whether it leaned and fixes itself. It's both a search tree and a balanced tree.

To know whether a node is lopsided, the AVL stores each node's height and computes its balance factor: left subtree's height minus right subtree's height. A leaf has height 0 and an empty child counts as βˆ’1. If the balance factor is βˆ’1, 0 or 1, the node is fine. If it's 2 or more, or βˆ’2 or less, it's unbalanced and needs a rotation.

Rotation is the AVL's key operation: it straightens an unbalanced node without changing the inorder sequence, so the tree is still a search tree. If a node is heavy on the left and its left child is too, a right rotation is done: the child moves up and the node moves down to its right. If it's heavy on the right and its right child is too, the left rotation, its mirror image, is done.

Sometimes a single rotation isn't enough. If a node is heavy on the left but its left child is heavy on the right, you have to rotate twice: first the child to the left and then the node to the right. The mirror case, heavy on the right with the child heavy on the left, is fixed by rotating the child to the right and then the node to the left. With the node's and its child's balance factors you know which of the 4 cases it is.

Inserting and deleting in an AVL work like in a regular search tree, with one more step: after the change, you go up from the touched node to the root, updating heights and rotating where needed. Searching doesn't change at all: it's the same search tree lookup. Since the height stays at about log n, everything is O(log n).

AVL trees are good for storing lots of data when searching is very frequent and inserting or deleting is rare, and for database indexes. There's another widely used balanced search tree: the red-black tree. It's less strict about balance, so it does fewer rotations when inserting and deleting, and on average those operations cost it less. Java uses it, for example, inside its HashMap.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

A tree that straightens itself