#pragma once #include using namespace std; class avlTree { private: class node { public: double data; node* left; node* right; int height; node(double x) { data = x; left = nullptr; right = nullptr; height = 0; } }; //uh oh, p's height value is sus.. //set it to the correct number. void updateHeight(node* p) { p->height = 1 + max(height(p->left), height(p->right)); } void leftRotation(node*& p) { node* A = p; node* B = p->right; node* bl = B->left; A->right = bl; B->left = A; p = B; updateHeight(A); updateHeight(B); } void rightRotation(node*& p) { node* A = p; node* B = p->left; node* br = B->right; A->left = br; B->right = A; p = B; updateHeight(A); updateHeight(B); } void rightLeftRotation(node * &p) { rightRotation(p->right); leftRotation(p); } void leftRightRotation(node*& p) { leftRotation(p->left); rightRotation(p); } //uh oh, p's balance is sus... //check if p is AVL balanced //If not, perform the proper rotation. void checkFixBalance(node*& p) { if (height(p->left) - height(p->right) >= 2) {//left height is too high if (height(p->left->left) > height(p->left->right)) rightRotation(p); else leftRightRotation(p); } else if (height(p->right)-height(p->left) >= 2) {//right height is too high if (height(p->right->right) > height(p->right->left)) leftRotation(p); else rightLeftRotation(p); } else { //The node is balanced!!! don't do anything. } } //Insert x into the tree rooted at node p. void insert(node*& p, double x) { if (p == nullptr)//tree is empty) p = new node(x); else { if (x < p->data) { //insert to the left insert(p->left, x);//the left tree) } else { //insert to the right insert(p->right, x); } updateHeight(p); checkFixBalance(p); } } node* root; //print all items in tree rooted at node p. //In-order traversal void display(node* p) { if (p == nullptr) { //don't do anything, no nodes } else { display(p->left); cout << p->data << endl; display(p->right); } } //return the height of tree rooted at node p. int height(node* p) { if (p == nullptr) return -1; else return p->height; } public: avlTree() { root = nullptr; } void insert(double x) { insert(root, x); } void display() { display(root); } int height() { return height(root); } };