Recall that searching in a binary search tree is O(ln n)
only if the tree is "balanced". If the tree is not balanced, it can turn into
a list, and searching would then be O(n)
Our goal: a way to keep a tree "balanced".
An AVL tree is a binary search tree that is height-balanced.
Height-balanced means that for every node in the tree, the height
of the left and right subtrees differ by at most one.
The height of a tree is the number of nodes in the longest path
from the root to any leaf.
Examples of the heights of trees:
Examples of AVL trees:
Examples of tree that are not AVL tres:
The name "AVL" comes from the Russian mathematicians who developed this
tree in 1962: G.M. Adel'son-Vel'skii and E.M. Landis.
We keep an AVL tree height-balance by reorganizing the tree when we inset
or delete elements. These reorganizations are accomplished by efficient
operations called rotations.
Rotations
Rotations are operations which restore the height-balance of a
tree that is slightly "height-imbalanced".
To perform rotations efficiently, we store an additional piece of
information at each node: the balance factor of that node.
In AVL trees, the balance factor of any node is -1, 0, or 1.
Rotations convert a tree with one node +2 or -2 into an AVL tree.
Inserting into an AVL Tree
We will assume we are inserting to the right subtree of a node. Inserting
into the left subtree is handled by a rotate right or a double
rotate right, the "mirror-images" of the cases shown below.
In each case, we have just inserted a new node into the tree, and the
resulting tree is no longer balanced. Each case shows how to restore the
balance of the tree.
Case 1: x is +2, y is +1 (new node has been inserted
into c)
Case 2: x is +2, y is -1 (new node has been inserted
into b or c)
Case 3: x is +2, y is 0
We can ignore this case, because it cannot happen after inserting
one element into an AVL tree. The new element must have been inserted into
either b or c. But then the other (b or c)
would have height h+1 before the insertion and x would have
had a balance factor of +2, so the tree could not have been an AVL tree.