The key invariant in the AVL tree is that the balance coefficient of each node is -1, 0, or +1. Here, the "balance factor" is the difference in height between the left and right subtrees. +1 means the left subtree is one higher than the right subtree, -1 means the left subtree is shorter than the right subtree, and 0 means the subtrees are the same size. This information is usually cached at each node.
When you get a node with a balance ratio of -2 or +2, you will need to make a turn. Here one possible setting is possible when a turn is required:
u (-2) / \ A v (-1) / \ BC
If we fill the heights of these trees, we get
uh + 2 / \ h-1 A vh + 1 / \ h-1 BC h
If this happens, then with one correct rotation you will get
v h+1 / \ hu C h / \ h-1 AB h-1
And hey! The tree is balanced. A mirror image of this tree could also be fixed with one rotation to the left.
All rotations of AVL trees can be determined simply by listing possible balance factors in a small range, and then determining which rotations should be applied at each step. I will leave this as an exercise for the reader. :-) If you just want to find the answers, the WL article on AVL trees has a nice image that summarizes all the twists you might need to apply.
Hope this helps!
source share