Avl
Avl
#include <bits/stdc++.h>
using namespace std;
class AVLTree {
private:
struct Node {
string key;
string value;
int balanceFactor;
Node* left;
Node* right;
Node(string k, string v) : key(k), value(v), balanceFactor(0), left(nullptr), right(nullptr) {}
};
Node* root;
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;
return y;
}
return node;
}
public:
AVLTree() : root(nullptr) {}
void displayInorder() {
displayWithBalance(root, "inorder");
}
void displayLevelOrder() {
displayWithBalance(root, "levelorder");
}
};
int main() {
AVLTree tree;
int choice;
string key;
string value;
while (true) {
cout << "\nMenu:\n";
cout << "1. Insert\n";
cout << "2. Display Inorder (with balance factor)\n";
cout << "3. Display Level Order (with balance factor)\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter key to insert: ";
cin >> key;
cout << "Enter value: ";
cin >> value;
cout << "Tree before insertion:\n";
tree.displayInorder();
cout << "\n";
tree.insert(key, value);
cout << "Tree after insertion:\n";
tree.displayInorder();
cout << "\nKey-value pair inserted.\n";
break;
case 2:
cout << "Inorder traversal with balance factors: \n";
tree.displayInorder();
break;
case 3:
cout << "Level order traversal with balance factors: \n";
tree.displayLevelOrder();
break;
case 4:
cout << "Exiting...\n";
return 0;
default:
cout << "Invalid choice. Try again.\n";
}
}
return 0;
}
OUTPUT:
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 1
Enter key to insert: H
Enter value: h
Tree before insertion:
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 1
Enter key to insert: K
Enter value: k
Tree before insertion:
H:h:0
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 1
Enter key to insert: O
Enter value: o
Tree before insertion:
H : h : -1
K:k:0
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 1
Enter key to insert: E
Enter value: e
Tree before insertion:
H:h:0
K:k:0
O:o:0
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 1
Enter key to insert: F
Enter value: f
Tree before insertion:
E:e:0
H:h:1
K:k:1
O:o:0
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: 3
Level order traversal with balance factors:
K:k:1
F:f:0
O:o:0
E:e:0
H:h:0
Menu:
1. Insert
2. Display Inorder (with balance factor)
3. Display Level Order (with balance factor)
4. Exit
Enter your choice: