Professional Documents
Culture Documents
use, single right or single left. As we can see that tree is left
heavy so we can use only right rotation. But Single right
rotation does not make the tree balanced. Let us see why?
X
Right Rotation
Unbalanced Tree
Unbalanced Tree
From above example we can see that single right rotation doesnt make the
tree balanced. Right rotation produces another unbalanced tree having
BF =-2 (node X). So single rotation is not enough to restore back its
balanced property, so we need double rotation. (Left-Right rotation)
Lets perform double rotation (Left-Right rotation) on a tree as given
below.
Z
Z
Left Rotation
at Node X
Right Rotation
at node Z
X
Y
Unbalanced Tree
Balanced Tree
Right Rotation at
Node Z
Left Rotation at
Node X
Y
Z
NULL
NULL
Note: Double Left Right rotation = First perform Single Left Rotation at left Child of node Z
Example
8
Left Rotation
at node 4
4
6
6
Right Rotation
at node 8
6
4
Insert 2
Insert 3
6
8
Right Rotation
at node 4
4
Left Right Rotation
6
3
6
8
Left Rotation
at node 2
2
3
Y
B
Y
B
A
Y
Z
Left Rotation
X
Z
Right Rotation
B
C
A
C
OR
Y
B
A
Y
Z
Left Rotation
B
X
C
Z
Right Rotation
X
A
A
Left Right Rotation
Perform Right
rotation around
P (node Z)
P
P->left
Perform left
rotation around
P->left (node X)
Left Rotation
Right Rotation
X
Y
X
Null
node double_left_right_rotate(node P)
{
node Q;
P->left = single_left_rotate(p->left);
Q = single_right_rotate(P);
return Q;
}
Perform right
rotation around Y
P->left
B
A
Left Rotation
X
Z
Right Rotation
B
A
Example:BF = 2 - 0 = 2
20
30
10
15
20
Insert 13
30
10
15
15
20
10
Left-Right Rotation
13
Insert 11, 12
15
15
15
Insert 4
10
Left-Right Rotation
20
10
20
10
30
13
20
BF = 2
30
12
11
11
13
30
12
30
13
11
13
12
Insert 14
BF = 2
15
5
4
30
12
11
Left Rotation
20
10
12
15
14
30
13
10
13
20 Right Rotation
12
11
14
10
5
15
11
13
20
14
30