y rotate (xy) R x
/ \ ====> / \
x 3 1 y
/ \ rotate (xy) L / \
1 2 <==== 2 3
DOUBLE ROTATE (xyz) L
x 1. rotate (yz) R
\ 2. rotate (xz) L z
y =======> / \
/ x y
z DOUBLE ROTATE (xzy) R
1. rotate (xz) R
2. rotate (yz) L
<=======
The height of a leaf (no children) is defined to be 0. The height of an empty tree (no nodes) is defined to be -1.
It can be shown by induction that the height, H, of an AVL tree with n nodes satisfies lg(n+1)-1 < H < 1.44 lg(n+2)-1.
The balance factor of a node is defined to be Height(RightSubtree) - Height(LeftSubtree). Thus, in an AVL tree, the balance factor of each node will be in {-1, 0, +1}.
Insertion into an AVL tree may change change the balance factors of some nodes on the path from the inserted node to the root. Any balance factor will change by at most 1 and the resulting value might become illegal (i.e., -2 or +2). After determining the deepest node that is "illegal", one single or one double rotation suffices to fix up the entire tree. Details.
Deletion from an AVL tree is handled similarly, but O(lg n) rotations may be required.
Three cases: