Self Balancing Trees (Hackerrank)
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property.
We define balance factor for each node as :
balanceFactor = height(left subtree) - height(right subtree)
The balance factor of any node of an AVL tree is in the integer range [-1,+1]. If after any modification in the tree, the balance factor becomes less than −1 or greater than +1, the subtree rooted at this node is unbalanced, and a rotation is needed.
Code -
int height(node* root)
{
if(root)
return root->ht;
else
return -1;
}
void rotateright(node* &root)
{
node* temp= root->left;
root->left= root->left->right;
temp->right=root;
root->ht= 1+ ((height(root->right)>height(root->left))? height(root->right) : height(root->left));
temp->ht= 1+ ((height(temp->right)>height(temp->left))? height(temp->right) : height(temp->left));
root=temp;
}
void rotateleft(node* &root)
{
node* temp= root->right;
root->right=root->right->left;
temp->left=root;
root->ht= 1+ ((height(root->right)> height(root->left)) ? height(root->right) : height(root->left));
temp->ht = 1 + ((height(temp->right) > height(temp->left)) ? height(temp->right) : height(temp->left));
root = temp;
}
void rotateleftright(node* &root)
{
rotateleft(root->left);
rotateright(root);
}
void rotaterightleft(node* &root)
{
rotateright(root->right);
rotateleft(root);
}
void insert1(node* &root, int val)
{
if(root==NULL)
{
root= new node();
root->val= val;
root->left = NULL;
root->right = NULL;
root->ht=0;
}
else if(root->val > val)
{
insert1(root->left, val);
int balance = height(root->right) - height(root->left);
int leftbalance = height(root->left->right) - height(root->left->left);
if(balance == -2)
{
if(leftbalance==-1)
rotateright(root);
if(leftbalance==+1)
rotateleftright(root);
}
}
else if(root->val<val)
{
insert1(root->right, val);
int balance= height(root->right) - height(root->left);
int rightbalance= height(root->right->right)- height(root->right->left);
if(balance ==2)
{
if(rightbalance==1)
rotateleft(root);
if(rightbalance==-1)
rotaterightleft(root);
}
}
root->ht= 1+ ((height(root->right)>height(root->left))? height(root->right) : height(root->left));
}
node* insert(node* root, int val)
{
insert1(root, val);
return root;
}