Exp Avl Trees C
Exp Avl Trees C
-14
Theory:
Balance Factor:
The balance factor of any node must be one of {-1, 0, 1}. If it goes beyond
this range, the tree is rebalanced.
Rotations:
To maintain the balance of the tree after insertions and deletions, rotations are
performed:
1. Standard BST Insert: Insert the new node as in a regular binary search tree.
2. Update Heights: After the insertion, update the height of each node starting
from the newly inserted node up to the root.
3. Check Balance: For each node, check the balance factor. If the balance
factor is outside the range {-1, 0, 1}, perform the appropriate rotations.
4. Rebalance the Tree: Perform the necessary rotations (Left or Right
rotations) to restore balance.
1. Standard BST Delete: Delete the node as you would in a regular binary
search tree.
2. Update Heights: After deletion, update the height of the nodes from the
deleted node up to the root.
3. Check Balance: For each node, check the balance factor. If it is outside the
acceptable range, perform the necessary rotations.
Source Code:
#include <stdio.h>
#include <stdlib.h>
Node* rightRotate(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
return x;
}
Node* leftRotate(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
if (node == NULL) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = key;
newNode->left = newNode->right = NULL;
newNode->height = 1;
return newNode;
}
return node;
}
if (root->left == NULL) {
Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node* temp = root->left;
free(root);
return temp;
}
return root;
}
int main() {
Node* root = NULL;
return 0;
}
Output: