Bird
Raised Fist0
Data Structures Theoryknowledge~6 mins

AVL tree rotations in Data Structures Theory - Full Explanation

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Balancing a tree is crucial to keep searching fast. When a tree becomes uneven, it slows down operations. AVL tree rotations fix this by rearranging nodes to keep the tree balanced.
Explanation
Why Balance Matters
A balanced tree keeps its height small, so searching, inserting, and deleting happen quickly. If one side grows too tall, these operations slow down. AVL trees use rotations to restore balance after changes.
Keeping the tree balanced ensures fast operations.
Single Right Rotation (LL Rotation)
This rotation fixes a left-heavy imbalance caused by inserting into the left child’s left subtree. It moves the left child up and the root down to the right, restoring balance.
Single right rotation corrects left-left imbalances.
Single Left Rotation (RR Rotation)
This rotation fixes a right-heavy imbalance caused by inserting into the right child’s right subtree. It moves the right child up and the root down to the left, restoring balance.
Single left rotation corrects right-right imbalances.
Left-Right Rotation (LR Rotation)
This double rotation fixes a left-right imbalance caused by inserting into the left child’s right subtree. It first rotates the left child to the left, then the root to the right.
Left-right rotation fixes left-right imbalances with two steps.
Right-Left Rotation (RL Rotation)
This double rotation fixes a right-left imbalance caused by inserting into the right child’s left subtree. It first rotates the right child to the right, then the root to the left.
Right-left rotation fixes right-left imbalances with two steps.
Real World Analogy

Imagine a seesaw with kids on both sides. If one side gets too heavy, the seesaw tips. To fix it, kids move around or swap places to balance it again. AVL rotations are like these moves to keep the seesaw level.

Why Balance Matters → Seesaw tipping when one side is heavier
Single Right Rotation (LL Rotation) → A kid on the left side moves closer to the center to balance
Single Left Rotation (RR Rotation) → A kid on the right side moves closer to the center to balance
Left-Right Rotation (LR Rotation) → A kid on the left side first moves right, then the seesaw adjusts
Right-Left Rotation (RL Rotation) → A kid on the right side first moves left, then the seesaw adjusts
Diagram
Diagram
Before LL Rotation:
    z
   /
  y
 /
x

After LL Rotation:
    y
   / \
  x   z

Before RR Rotation:
  x
   \
    y
     \
      z

After RR Rotation:
    y
   / \
  x   z

LR Rotation:
  z
 /
x
 \
  y

After LR Rotation:
    y
   / \
  x   z

RL Rotation:
  x
   \
    z
   /
  y

After RL Rotation:
    y
   / \
  x   z
Shows how nodes move during each AVL rotation to restore balance.
Key Facts
AVL TreeA self-balancing binary search tree that maintains height balance using rotations.
Balance FactorThe height difference between left and right subtrees of a node.
Single RotationA rotation that fixes simple left-left or right-right imbalances.
Double RotationA two-step rotation that fixes left-right or right-left imbalances.
LL RotationSingle right rotation to fix left-left imbalance.
RR RotationSingle left rotation to fix right-right imbalance.
Code Example
Data Structures Theory
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.height = 1

class AVLTree:
    def get_height(self, node):
        return node.height if node else 0

    def get_balance(self, node):
        return self.get_height(node.left) - self.get_height(node.right) if node else 0

    def right_rotate(self, z):
        y = z.left
        T3 = y.right
        y.right = z
        z.left = T3
        z.height = 1 + max(self.get_height(z.left), self.get_height(z.right))
        y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
        return y

    def left_rotate(self, z):
        y = z.right
        T2 = y.left
        y.left = z
        z.right = T2
        z.height = 1 + max(self.get_height(z.left), self.get_height(z.right))
        y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
        return y

    def insert(self, root, key):
        if not root:
            return Node(key)
        elif key < root.key:
            root.left = self.insert(root.left, key)
        else:
            root.right = self.insert(root.right, key)

        root.height = 1 + max(self.get_height(root.left), self.get_height(root.right))
        balance = self.get_balance(root)

        # LL
        if balance > 1 and key < root.left.key:
            return self.right_rotate(root)
        # RR
        if balance < -1 and key > root.right.key:
            return self.left_rotate(root)
        # LR
        if balance > 1 and key > root.left.key:
            root.left = self.left_rotate(root.left)
            return self.right_rotate(root)
        # RL
        if balance < -1 and key < root.right.key:
            root.right = self.right_rotate(root.right)
            return self.left_rotate(root)

        return root

    def pre_order(self, root):
        return [] if not root else [root.key] + self.pre_order(root.left) + self.pre_order(root.right)

avl = AVLTree()
root = None
for key in [10, 20, 30, 40, 50, 25]:
    root = avl.insert(root, key)
print(avl.pre_order(root))
OutputSuccess
Common Confusions
Thinking all rotations are single-step.
Thinking all rotations are single-step. Some imbalances need two rotations (double rotations) to fix, not just one.
Believing rotations change the binary search tree order.
Believing rotations change the binary search tree order. Rotations only rearrange nodes to balance the tree but keep the search order intact.
Assuming balance factor is always zero after rotation.
Assuming balance factor is always zero after rotation. Balance factors after rotation can be -1, 0, or 1, all indicating a balanced node.
Summary
AVL tree rotations keep the tree balanced to ensure fast searching and updating.
Single rotations fix simple imbalances, while double rotations fix more complex ones.
Rotations rearrange nodes without changing the binary search tree order.

Practice

(1/5)
1. What is the main purpose of rotations in an AVL tree?
easy
A. To keep the tree balanced for faster search and update operations
B. To delete nodes from the tree
C. To increase the height of the tree
D. To sort the nodes in ascending order

Solution

  1. Step 1: Understand AVL tree balance

    AVL trees maintain balance by ensuring the height difference between left and right subtrees is at most 1.
  2. Step 2: Role of rotations

    Rotations adjust the tree structure to restore balance after insertions or deletions, improving operation speed.
  3. Final Answer:

    To keep the tree balanced for faster search and update operations -> Option A
  4. Quick Check:

    AVL rotations = balance tree = faster operations [OK]
Hint: Rotations fix balance to keep operations fast [OK]
Common Mistakes:
  • Thinking rotations delete nodes
  • Believing rotations sort nodes
  • Assuming rotations increase tree height
2. Which of the following is the correct syntax to perform a right rotation on a node x in an AVL tree?
easy
A. rightRotate(x)
B. x.rightRotate()
C. rotateRight(x)
D. rotate(x, 'right')

Solution

  1. Step 1: Identify common function naming

    In AVL tree implementations, the function to rotate right is commonly named rotateRight(node).
  2. Step 2: Check options

    rotateRight(x) matches the common syntax. rightRotate(x) and x.rightRotate() are less standard, and rotate(x, 'right') is a generic call not typical in AVL code.
  3. Final Answer:

    rotateRight(x) -> Option C
  4. Quick Check:

    Right rotation function = rotateRight(node) [OK]
Hint: Look for 'rotateRight' as standard right rotation function name [OK]
Common Mistakes:
  • Using method calls on node objects incorrectly
  • Confusing rightRotate with rotateRight
  • Using generic rotate function without direction
3. Given the following AVL tree insertion sequence: Insert 10, then 20, then 30. Which rotation will be performed to balance the tree?
medium
A. Left rotation
B. Right rotation
C. Left-Right rotation
D. Right-Left rotation

Solution

  1. Step 1: Analyze insertion order and imbalance

    Inserting 10, then 20, then 30 creates a right-heavy chain (10 -> 20 -> 30), causing imbalance at 10.
  2. Step 2: Determine rotation type

    This is a Right-Right case, fixed by a single left rotation at node 10.
  3. Final Answer:

    Left rotation -> Option A
  4. Quick Check:

    Right-heavy imbalance = left rotation [OK]
Hint: Right-heavy chain = left rotation to balance [OK]
Common Mistakes:
  • Choosing right rotation for right-heavy imbalance
  • Confusing Left-Right with Right-Right cases
  • Ignoring the order of insertions
4. You implemented a left-right rotation but the AVL tree remains unbalanced after insertion. What is the most likely error?
medium
A. Performed rotations in wrong order
B. Used right rotation instead of left rotation
C. Inserted duplicate keys
D. Forgot to update node heights after rotation

Solution

  1. Step 1: Understand rotation steps

    Left-right rotation requires two rotations and updating node heights to maintain AVL properties.
  2. Step 2: Identify common mistake

    Not updating heights after rotations causes incorrect balance checks, leaving tree unbalanced.
  3. Final Answer:

    Forgot to update node heights after rotation -> Option D
  4. Quick Check:

    Update heights after rotations to keep balance [OK]
Hint: Always update heights after rotations [OK]
Common Mistakes:
  • Doing rotations in wrong order
  • Mixing up left and right rotations
  • Ignoring height updates
5. After inserting nodes 30, 20, 25 into an empty AVL tree, which rotation(s) will balance the tree?
hard
A. Single left rotation at 20
B. Left-Right rotation at 30
C. Single right rotation at 30
D. Right-Left rotation at 20

Solution

  1. Step 1: Analyze insertion sequence and imbalance

    Inserting 30, then 20, then 25 creates a left-right case: 30 has left child 20, which has right child 25.
  2. Step 2: Identify correct rotation

    Left-right imbalance requires a left rotation on 20 followed by a right rotation on 30, called a left-right rotation.
  3. Final Answer:

    Left-Right rotation at 30 -> Option B
  4. Quick Check:

    Left-right case = left-right rotation [OK]
Hint: Left child with right-heavy subtree = left-right rotation [OK]
Common Mistakes:
  • Choosing single rotations instead of double
  • Confusing left-right with right-left cases
  • Rotating wrong nodes