struct Node *insert(struct Node *ptr, int data) {
if (ptr == NULL) {
// Create a new node and assign required values
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode -> data = data;
newNode -> left = newNode -> right = NULL;
newNode -> height = 1;
return newNode;
}
if (data < ptr -> data)
ptr -> left = insert(ptr -> left, data);
else if (data > ptr -> data)
ptr -> right = insert(ptr -> right, data);
// Assign height as the max height of left subtree and right subtree
ptr -> height = nodeHeight(ptr);
// Check balance factor and perform rotation
if (balanceFactor(ptr) == 2 && balanceFactor(ptr -> left) == 1)
return LLRotation(ptr);
else if (balanceFactor(ptr) == 2 && balanceFactor(ptr -> left) == -1)
return LRRotation(ptr);
else if (balanceFactor(ptr) == -2 && balanceFactor(ptr -> right) == 1)
return RLRotation(ptr);
else if (balanceFactor(ptr) == -2 && balanceFactor(ptr -> right) == -1)
return RRRotation(ptr);
return ptr;
}
int nodeHeight(struct Node *ptr) {
int leftHeight, rightHeight;
leftHeight = ptr && ptr -> left ? ptr -> left -> height : 0;
rightHeight = ptr && ptr -> right ? ptr -> right -> height : 0;
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
int balanceFactor(struct Node *ptr) {
int leftHeight, rightHeight;
leftHeight = ptr && ptr -> left ? ptr -> left -> height : 0;
rightHeight = ptr && ptr -> right ? ptr -> right -> height : 0;
return leftHeight - rightHeight;
}