AVL Tree - Left Rotate and Right Rotate (in LL, RR, LR and RL conditions)
Hence Algorithm of left rotating a node in AVL tree :
treeNode leftRotate(cdn){
treeNode NR = cdn.right;
cdn.right = NR.left; // any left child of NR will be right child of cdn
NR.left = cdn;
// After doing rotation, we have to adjust the height of cdn and NR now
cdn.height = calculateHeight(cdn);
NR.height = calculateHeight(NR);
// finally we will return newRoot to the recursively calling function
return NR;
}
The algorithm of right rotate is just the mirror image of this :
treeNode rightRotate(cdn){
treeNode NR = cdn.left;
cdn.left= NR.right; // any right child of NR will be left child of cdn
NR.right= cdn;
// After doing rotation, we have to adjust the height of cdn and NR now
cdn.height = calculateHeight(cdn);
NR.height = calculateHeight(NR);
// finally we will return newRoot to the recursively calling function
return NR;
}
- In LL condition, we do a rightRotate on cdn
- In RR condition, we do a leftRotate on cdn
- In RL condition, we do:
- first, rightRotate on cdn.right
- then, leftRotate on cdn
- In LR condition, we do:
- first, leftRotate on cdn.left
- then, rightRotate on cdn
AVL tree is a special case of Binary Search tree in which we try to make a balanced tree by calculating the balance on each node and doing rotation based on LL, LR, RL and RR condtions in order to make the tree balanced.
Comments
Post a Comment