Вы находитесь на странице: 1из 3

Rotation in AVL Tree

As we know insertion and deletion of node/data from AVL Tree can leave
behind the tree to be unbalanced. (I.e. violates AVL-ness property of the tree)

So the idea behind maintaining the AVL-ness of an AVL tree is that whenever
we insert or delete an item, and if we have violated the AVL-ness property
of the tree, we must then restore its AVL-ness property by performing a set of
manipulations on the tree and these manipulation are known as Rotation.

Insert or delete operation may cause balance factor to become 2 or 2


for some node leaving behind the tree as Non-AVL.

Let us suppose an insert operation may cause AVL tree to become


unbalanced. So we will see how to restore it back to AVL Tree as:
Only nodes on the path from insertion point to root node have
possibly changed in height. So after the Insert, move toward the root,
node by node, updating heights (checking balance factor at each node).
If balance factor (difference h_left - h_right) of any node is 2 or 2, adjust
tree by performing rotation around the node (node having balance
factor 2 or -2).

A node is unbalanced when the absolute height difference between the


left and right sub-trees is greater than 1 or less than -1.

There are 2 types of Rotations: Single Rotation.


Double Rotation.

Single Rotation (Outside Case)

There are two cases in single rotation. Right Rotation and Left Rotation"
Right Rotation

Left Rotation

Insertion into left sub-tree of left


child of node z.

Insertion into right sub-tree of right


child of node X.

Y
Z

X
Insert X here
Need of Right Rotation in this case

Insert Z here
Need of Left Rotation in this case

Double Rotation (Inside Case):

Req
There are two cases in double rotation. Left-Right and Right-Left Rotation.
Left-Right Rotation

Right-Left Rotation

Insertion into right sub-tree of


left child of node Z.

Insertion into left sub-tree of right


child of node X.
X

X
Y

Insert Y here

NeedRotation
of Left-Right
Rotation
Single
(Outside
Case)

Insert Y here

Need of Right-Left Rotation

Вам также может понравиться