40C. Review of How to Do Rotations


Zig-zig and zig-zag

If a node v is already height-balanced, you should not do any kind of rotation on it. Leave it alone. But if it is not height-balanced, decide whether a single rotation or a double rotation is appropriate as follows. Starting at v, take two steps downward, each time moving into the higher subtree. For example, suppose v is the root of the following tree.

The left subtree of v has height 1, but the right subtree has height 3. So a rotation is called for. Imagine taking two steps toward the higher subtree: starting at 20, step to 30 and then to 40.

If the two steps are in the same direction (two right steps or two left steps), as they are in this example, we call it a zig-zig, and a single rotation is called for. Performing the single rotation yields the following tree.

If the two steps are in opposite directions (a left step and a right step), we call it a zig-zag. In that case, a double-rotation is called for. For example, suppose that v is the root of the following tree.

Node v is out of balance, and two steps toward the higher subtree take you from 20 to 30 (a right step) then from 30 to 25 (a left step). A double rotation is called for here. Performing the double rotation yields the following.


Perform rotations from bottom to top

When performing a rotation at node v, it is important for the subtrees of v to be height-balanced already. That is ensured by performing rotations from bottom to top. If you perform an insertion, for example, you start by following a path downward to the insertion point. Then walk back up that path. At each node, check whether a rotation is needed. If so, then perform it. It is possible that more than one rotation is needed. Just do each one that is required, in bottom-to-top order. Here is an example. The first step is to use the basic insertion algorithm, walking down the tree to the insertion point.

Now walk back up the same path that you just walked down. The node holding 38 is already height-balanced. But the node holding 44 is not. If you take two steps downward from 44, each toward the higher subtree, you take one step to the left and then one step to the right. That is a zig-zag, and it calls for a double rotation. The subtree rotation is

so the full tree is now

Continuing to walk back up the insertion path takes you to 30 and 50. Since those nodes are already height-balanced, you make no changes to them.

Here is another example.

Now walk back up the insertion path. The nodes containing 90, 85 and 80 are already height-balanced. But the root is not height-balanced, since its left subtree has height 2 and its right subtree has height 4. So in this case, a rotation is done at the root of the tree. Two steps downward from the root toward the higher subtree are both to the right, so this is a zig-zig operation, calling for a single rotation. The rotation is as follows.