AVL Rotations in Javascript

To balance itself, an AVL tree may perform the following four kinds of rotations:

  • Left rotation
  • Right rotation
  • Left-Right rotation
  • Right-Left rotation

The first two rotations are single rotations and the next two rotations are double rotations. To have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's understand them one by one.

Left Rotation

If a tree becomes unbalanced when a node is inserted into the right subtree of the right subtree, then we perform a single left rotation:

Before Left Rotation A B C Rotate Left After Left Rotation B A C

In our example, node A has become unbalanced as a node is inserted in the right subtree of A's right subtree. We perform the left rotation by making A the left-subtree of B. This rotation is also called an LL rotation. Let us look at how we can implement it:

function rotationLL(node) {
    let tmp = node.left;
    node.left = tmp.right;
    tmp.right = node;
    return tmp;
}

Right Rotation

AVL tree may become unbalanced if a node is inserted in the left subtree of the left subtree. The tree then needs a right rotation.

Before Right Rotation C B A Rotate Right After Right Rotation B A C

As depicted, the unbalanced node becomes the right child of its left child by performing a right rotation. This is also called an RR rotation. Let us see how it looks in code:

function rotationRR(node) {
    let tmp = node.right;
    node.right = tmp.left;
    tmp.left = node;
    return tmp;
}

Left-Right Rotation

Double rotations are a slightly complex version of already explained versions of rotations. To understand them better, we should take note of each action performed while rotation. Let's first check how to perform the Left-Right rotation. A left-right rotation is a combination of left rotation followed by a right rotation.

State Action
C A B A node has been inserted into the right subtree of the left subtree. This makes C an unbalanced node. These scenarios cause AVL tree to perform the left-right rotation.
C B A We first perform the left rotation on the left subtree of C. This makes A, the left subtree of B.
B A C We shall now right-rotate the tree, making B the new root node of this subtree. C now becomes the right subtree of its own left subtree.
B A C The tree is now balanced.

This is also called an LR rotation as we first perform a left rotation followed by a right rotation. This can be implemented using the previous 2 methods as follows:

function rotationLR(node) {
    node.left = rotationRR(node.left);
    return rotationLL(node);
}

Right-Left Rotation

Updated on: 2026-03-15T23:18:59+05:30

491 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements