250 likes | 276 Views
Learn the mechanics of AVL tree rotations with detailed explanations and examples for RR, LL, RL, and LR imbalances.
E N D
-1 10 1 1 7 40 -1 0 1 0 45 3 8 30 0 -1 0 0 0 60 35 1 20 5 0 25 AVL Search Tree put(9)
put(9) -1 10 0 1 1 7 40 -1 0 1 -1 0 45 3 8 30 0 -1 0 0 0 0 60 35 1 9 20 5 0 25 No imbalance
RR imbalance - put(29) 10 -1 1 1 7 40 -1 0 1 0 45 3 8 30 0 -1 0 0 0 60 35 20 1 20 5 0 25
RR imbalance - put(29) 10 -1 1 7 1 40 0 0 8 -1 3 1 45 30 0 0 0 1 -1 0 5 -2 60 35 20 20 RR imbalance: new node is in right subtree of right subtree of blue node (node with bf = -2) 0 -1 25 0 29 FIX: Single rotation
RR imbalance - put(29) 10 -1 1 7 1 40 0 0 8 -1 3 1 45 30 0 0 0 1 0 5 0 60 35 25 0 0 20 29 AFTER ROTATION
AVL Rotations • RR • LL • RL • LR
LL imbalance - put(1) -1 10 1 0 7 40 0 0 0 50 3 30 0 0 0 0 35 45 60 20 20
LL imbalance - put(1) -1 10 2 1 0 7 40 0 1 0 0 50 3 30 0 0 0 0 0 1 35 45 60 20 20 LL imbalance => new node is in left subtree of left subtree of blue node (node with bf = 2) FIX: Single right rotation
LL imbalance - put(1) -1 10 0 0 3 40 0 0 0 0 50 1 7 30 0 0 0 0 35 45 60 20 20 AFTER rotation
LR imbalance - put(8) 1 10 0 0 3 40 0 0 2 4
LR imbalance - put(8) 2 1 10 -1 0 3 40 0 -1 2 4 0 8 LR imbalance => new node is in right subtree of left subtree of blue node (node with bf = 2) FIX: Double rotation
LR imbalance - put(8) 2 1 -1 10 0 3 40 LL ROTATION 2 4 RR ROTATION 8 LR rotation is an RR rotation followed by LL rotation
LR imbalance - put(8) 2 1 -1 10 0 4 40 LL ROTATION 3 8 2 AFTER FIRST ROTATION
LR imbalance - put(8) 0 4 1 0 10 3 0 0 0 8 2 40 AFTER SECOND ROTATION
RL imbalance - put(5) -1 2 0 0 8 1 0 0 9 7
RL imbalance - put(5) -2 -1 2 1 0 0 8 1 1 0 0 9 7 0 5 RL imbalance => new node is in left subtree of right subtree of blue node (node with bf = -2) FIX: Double rotation
RL imbalance - put(5) -2 -1 2 1 0 0 8 1 1 RR ROTATION 0 9 7 0 5 LL ROTATION RL rotation is an LL rotation followed by an RR rotation
RL imbalance - put(5) -2 -1 2 -1 0 0 7 1 -1 RR ROTATION 0 8 5 0 9 AFTER FIRST ROTATION
RL imbalance - put(5) 0 7 0 -1 8 2 0 0 0 9 1 5 AFTER SECOND ROTATION
delete(45) 2 1 10 0 0 -1 6 40 0 0 0 45 3 8 0 0 0 0 1 7 5 9
delete(45) -1 6 0 1 3 10 0 After R0 rotation 0 0 0 1 5 40 8 0 0 7 9
delete(45) 2 1 10 0 1 -1 6 40 0 0 0 45 3 8 0 0 1 5
delete(45) 0 6 0 0 3 10 0 After R1 rotation 0 0 0 1 5 40 8
delete(45) 2 1 10 0 -1 -1 6 40 0 0 0 45 3 8 0 0 7 9
delete(45) 0 8 0 0 6 10 0 0 0 0 3 7 9 40 After R-1 rotation