DrawCode Algorithm Visualizer • Tree • Hard

AVL Tree Rotation

Tags: Tree, Balanced BST, AVL, Rotation

1. One-Liner

AVL rotations are local tree surgeries (left/right) that restore balance while keeping BST order after inserts or deletes.


2. The Problem It Solves

After updating an AVL tree, a node’s balance factor (left height − right height) can become ±2. Rotations rehang subtrees so heights differ by at most 1 again—keeping O(log n) height.


3. The Core Idea

A right rotation at unbalanced node y with heavy left child x promotes x to root of this subtree; x’s old right becomes y’s new left. Left rotation is mirror. LR/RL double rotations compose two singles on the grandchild path.


4. How It Works (Step-by-Step)

StepAction
1Detect imbalance: `balance> 1` at node z.
2If left-heavy and left child left-heavyright rotate(z).
3If left-heavy and left child right-heavyleft rotate(left child), then right rotate(z).
4Mirror cases for right-heavy.
5Update heights from leaves up after each rotation.

5. Dry Run Example

Insert into left-left pattern: imbalance at A, heavy left B, B’s left C. Single right(A) makes B root, A right child, BST order preserved.


6. Key Properties

PropertyDetail
InorderUnchanged across rotation
HeightDrops at the problem spot
CasesLL, RR, LR, RL

7. Where It Is Used

ContextUse
Databases / mapsGuaranteed worst-case log n ops
Real-timePredictable latency vs unbalanced BST

8. Interview Tips

Draw before/after pointers. State balance factor definition. Know four cases by pattern (not memorizing letters only). Compare with red-black (looser balance, fewer rotations amortized).


9. Comparison with Other Algorithms

StructureHeightRotation cost
AVLStricter O(log n)More rotations on insert
Red-black≤ 2× black heightFewer rotations typical
TreapRandomized expected logHeap key + BST

10. Complexity

----
RotationO(1) pointer changes
Insert/Delete overallO(log n) find + O(1)–O(log n) rebalancing

Implementation Example (PYTHON)

class AVLNode:
    def __init__(self, k):
        self.key, self.h = k, 1
        self.left = self.right = None

def height(n): return 0 if not n else n.h

def rotate_right(y):
    x = y.left
    t2 = x.right
    x.right, y.left = y, t2
    y.h = 1 + max(height(y.left), height(y.right))
    x.h = 1 + max(height(x.left), height(x.right))
    return x

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer