void RotateUp(AVLNode* cur) { AVLNode* k = cur->parent; if (k == NULL) { return; } AVLNode* parent = k->parent; if (k->left == cur) { k->left = cur->right; if (k->left) { k->left->parent = k; } cur->right = k; k->parent = cur; } else { k->right = cur->left; if (k->right) { k->right->parent = k; } cur->left = k; k->parent = cur; } replaceChild(parent, k, cur); fixHeight(k); fixHeight(cur); fixHeight(parent); fixSize(k); fixSize(cur); fixSize(parent); }
void TreeDB::rotateLeft(TreeNode*& rootQ) { //rotates the root to the left TreeNode* P = rootQ->right; rootQ->right = P->left; P->left = rootQ; //fixes the heights of the changed trees fixHeight(rootQ); fixHeight(P); //re assigns the root pointer (parent) rootQ = P; }
void TreeDB::rotateRight(TreeNode*& rootP) { //rotates the root to the right TreeNode* Q = rootP->left; rootP->left = Q->right; Q->right = rootP; //fixes the heights of the changed trees fixHeight(rootP); fixHeight(Q); //re assigns the root pointer (parent) rootP = Q; }
void makeBalance(AVLNode* cur) { AVLNode* prev = NULL; while (cur != NULL) { fixHeight(cur); fixSize(cur); int leftHeight = getHeight(cur->left); int rightHeight = getHeight(cur->right); if (leftHeight - rightHeight == 2) { int leftLeftHeight = getHeight(cur->left->left); int leftRightHeight = getHeight(cur->left->right); if (leftLeftHeight >= leftRightHeight) { cur = cur->left; RotateUp(cur); } else { cur = cur->left->right; RotateUp(cur); RotateUp(cur); } } else if (rightHeight - leftHeight == 2) { int rightLeftHeight = getHeight(cur->right->left); int rightRightHeight = getHeight(cur->right->right); if (rightRightHeight >= rightLeftHeight) { cur = cur->right; RotateUp(cur); } else { cur = cur->right->left; RotateUp(cur); RotateUp(cur); } } prev = cur; cur = cur->parent; } root_ = prev; }
void TreeDB::balance(TreeNode*& root) { fixHeight(root); //by convention, we are right heavy if(balanceFactor(root) == 2) { //if we have a zig-zag form, we must rotate right then left if(balanceFactor(root->right) < 0) { cout << "rebalancing..." << endl; rotateRight(root->right); } //if we have a linked list form, we only need to rotate left, //if we had a zig zag form, we already rotated right, now left cout << "rebalancing..." << endl; rotateLeft(root); } else if(balanceFactor(root) == -2) //left heavy { //if we have a zig-zag form, we must rotate left then right if(balanceFactor(root->left) > 0) { cout << "rebalancing..." << endl; rotateLeft(root->left); } //if we have a linked list form, we only need to rotate right, //if we had a zig zag form, we already rotated left, now right cout << "rebalancing..." << endl; rotateRight(root); } }