Rotation
- Algorithms course
- Intermediate
- Lesson 34/80
- 4 min
Single and double rotations restore balance.
Rotation
When the balance breaks in AVL a rotation is done. Right rotation: in a left-heavy case, brings the left child up.
In a right rotation: y = x.left, x.left = y.right, y.right = x. Now y is the new root, x its right child.
The rotation preserves the BST property and reduces height. It is O(1).
Four cases
AVL has four imbalance cases: left-left (right rotate), left-right (left then right rotate), right-right (left rotate), right-left (right then left rotate).
Left-right and right-left need double rotation: first a sub-rotation, then the main one. This fixes complex skews.
In every case the result: balance factor returns to -1,0,+1; the BST property is preserved.
Practice Right rotation
Write rotate_right(x). y = x.left, x.left = y.right, y.right = x, return y. Print 2 3 with root = Node(3); root.left = Node(2); root.left.left = Node(1); new_root = rotate_right(root); print(new_root.val, new_root.right.val).
Starter code
def rotate_right(x):
# Right rotationSample solution
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def rotate_right(x):
# Right rotation
y = x.left
x.left = y.right
y.right = x
return y
root = Node(3)
root.left = Node(2)
root.left.left = Node(1)
new_root = rotate_right(root)
print(new_root.val, new_root.right.val)Expected output
2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Right rotation
y = x.left
x.left = y.____
y.right = x
y = x.left
x.left = y.right
y.right = x
Explanation: right is right.
2 Rotation: match the terms
| Term | Meaning |
|---|---|
Left-left |
Right rotate |
Right-right |
Left rotate |
Left-right |
Left first |
Right-left |
Right first |
3 Which case does right rotation fix?
- Right-right
- Left-right
- Left-left Correct answer
- Right-left
Explanation: Left-left