AVL tree rotations are operations used to keep an AVL tree balanced after insertion or deletion. An AVL tree is a self-balancing binary search tree where the difference between the heights of left and right subtrees (called balance factor) should not be more than 1. When this balance is disturbed, rotations are applied to restore it.
There are four types of rotations: LL, RR, LR, and RL.
LL (Left-Left) Rotation: This case occurs when a node is inserted into the left subtree of the left child, making the tree left-heavy. To fix this, a single right rotation is performed. For example, if values are inserted in decreasing order like 30, 20, 10, the tree becomes unbalanced, and a right rotation makes 20 the new root with 10 as left child and 30 as right child.
RR (Right-Right) Rotation: This happens when a node is inserted into the right subtree of the right child, making the tree right-heavy. A single left rotation is used to fix it. For example, inserting 10, 20, 30 causes imbalance, and after left rotation, 20 becomes the root with 10 and 30 as its children.
LR (Left-Right) Rotation: This occurs when a node is inserted into the right subtree of the left child. It requires two rotations: first a left rotation on the left child, then a right rotation on the unbalanced node. For example, inserting 30, 10, 20 leads to this case, and after rotations, 20 becomes the root.
RL (Right-Left) Rotation: This happens when a node is inserted into the left subtree of the right child. It also requires two rotations: first a right rotation on the right child, then a left rotation on the unbalanced node. For example, inserting 10, 30, 20 results in this case, and 20 becomes the root after balancing.
These rotations ensure the AVL tree remains balanced, maintaining efficient search, insertion, and deletion operations.