void balanceAvl(struct node **root){ if(*root == NULL) return; int height_diff = 0; height_diff = height_difference(*root); if((*root)->lptr) balanceAvl(&(*root)->lptr); else balanceAvl(&(*root)->rptr); if(height_diff >= 2){ if(height_difference((*root)->lptr) >= 1) *root = leftLeftRotate(*root); else *root = leftRightRotate(*root); } else if(height_diff <= -2){ if(height_difference((*root)->rptr) <= -1) *root = rightRightRotate(*root); else *root = rightLeftRotate(*root); } else{ *root = *root; } }
void AVL<T,V>::insert(T Key, V Value){ // I created a new node to add to the AVL tree // and populated it with the Key/Value pair TreeNode<T,V>* newNode = new TreeNode<T,V>; TreeNode<T,V>* parentNode; newNode->left = NULL; newNode->right = NULL; newNode->key = Key; newNode->value = Value; parentNode = NULL; if (root == NULL) // If the AVL tree is empty, create a new start node. root = newNode; else // Otherwise, run through the tree and add it to the appropriate end. { TreeNode<T,V>* currentNode; currentNode = root; while(currentNode != NULL) // While the end of the AVL tree hasn't been reached { parentNode = currentNode; if (newNode->key < currentNode->key) // If the key being added is less then the current key, go left currentNode = currentNode->left; // Then set the current node to the next left node else // Otherwise go Right currentNode = currentNode->right; } if (newNode->key < parentNode->key) // Once the end is reached, { parentNode->left = newNode; // if the new key is less then it's parents key add it to the left if(height(root->left) - height(root->right) > 1) // if the height of the left side is greater then 1 { if(height(root->left->right) - height(root->left->left) > 1) leftLeftRotate(root); // do either the left right case else leftRotate(root); // or the left-left case } } else { parentNode->right = newNode; if(height(root->right) - height(root->left) > 1) { if(height(root->right->left) - height(root->right->right) > 1) rightRightRotate(root); else rightRotate(root); } } // I used this to make sure the tree was properly balanced // When included the height of both the right and left sides of the AVL tree were 30 // std::cout << height(root->left) << ", " << height(root->right) << std::endl; } }