Avl tree insertion
#include <bits/stdc++.h>
using namespace std;
struct Node {
int element;
struct Node *left, *right;
int height;
};
int height(Node *N) {
if (N == NULL) return 0;
return N->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node *newNode(int key) {
Node *node = new Node();
node->element = key;
node->left = node->right = NULL;
node->height = 1;
return node;
}
Node *rightRotate(Node *y) {
Node *x = y->left;
Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
Node *leftRotate(Node *x) {
Node *y = x->right;
Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(Node *N) {
if (N == NULL) return 0;
return height(N->left) - height(N->right);
}
Node *insert(Node *node, int key) {
if (node == NULL) return newNode(key);
if (key < node->element) {
node->left = insert(node->left, key);
} else if (key > node->element) {
node->right = insert(node->right, key);
} else {
return node;
}
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->element) {
return rightRotate(node);
} else if (balance > 1 && key > node->left->element) {
node->left = leftRotate(node->left);
return rightRotate(node);
} else if (balance < -1 && key > node->right->element) {
return leftRotate(node);
} else if (balance < -1 && key < node->right->element) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void preOrder(Node *root) {
if (root != NULL) {
cout << root->element << " ";
preOrder(root->left);
preOrder(root->right);
}
}
int main() {
Node *root = NULL;
int x, n, option;
cout << "1. Create AVL Tree\n";
cout << "2. End Program\n";
cout << "Enter your choice ";
cin >> option;
switch (option) {
case 1:
cout << "\nEnter no. of elements : ";
cin >> n;
root = NULL;
for (int i = 0; i < n; i++) {
cout << "Enter element of tree ";
cin >> x;
root = insert(root, x);
}
cout << "\nPreorder sequence:\n";
preOrder(root);
break;
}
return 0;
}