AVL树双重旋转错误

AVL Tree Double Rotation error

本文关键字:旋转 错误 AVL      更新时间:2023-10-16

我正在为学校做一个项目,该项目涉及使用迭代插入函数实现AVL树,我遇到了一个问题。

我不能100%确定我没有做什么,但我的程序没有给出正确的输出。

以下是我的插入函数:

bool AVLTree::insert(string ss, string na){
AVLNode* newNode = new AVLNode(ss, na);
updateHeight(newNode);
//Tree is empty, make the new Node the root of a new tree
if(getRoot() == nullptr){
    root = newNode;
    print();
    return true;
}
//Tree is not empty
else{
    AVLNode* checkPoint;
    checkPoint = root;
    while(checkPoint != nullptr){
        //If the ssn is already in the tree
        if(checkPoint->ssn.compare(newNode->ssn) == 0){
            return false;
        }
        else if(checkPoint->ssn.compare(newNode->ssn) > 0){
            if(checkPoint->left == nullptr){
                break;
            }
            checkPoint = checkPoint->left;
        }
        else{
            if(checkPoint->right == nullptr){
                break;
            }
            checkPoint = checkPoint->right;
        }
    }
    if(newNode->ssn.compare(checkPoint->ssn) < 0){
        checkPoint->left = newNode;
    }
    else{
        checkPoint->right = newNode;
    }
    updateHeight(checkPoint);
    balance(root);
    print();
    return true;
}

这是我到目前为止提出的功能,对于我的项目,我得到了平衡功能和updateHeight,我将在这里提供:

AVLNode* AVLTree::balance(AVLNode* node){
updateHeight(node);
if (balanceFactor(node) == 2) {
    if (balanceFactor(node->left) < 0) {
        node->left = rotateLeft(node->left); // for left right case
    }
    AVLNode* temp = rotateRight(node);
    updateHeight(temp);
    return temp;
}
if (balanceFactor(node) == -2) {
    if (balanceFactor(node->right) > 0) {
        node->right = rotateRight(node->right);  // for right left case
    }
    AVLNode* temp2 = rotateLeft(node);
    updateHeight(temp2);
    return temp2;
}
return node;

更新高度:

void AVLTree::updateHeight(AVLNode* node){
    int hl = height(node->left);
    int hr = height(node->right);
    node->height = (hl>hr ? hl : hr) + 1;
}

基本上,我的任务是实现插入和删除功能。我对avl树的输入顺序是:

5、8、9、3、6、7、5

我的输出是:

      8
     / 
    5   9
   / 
  3   6
 /     
2       7

应该在什么时候:

        6
     /     
    3       8
   /      / 
  2   5   7   9

回到我的插入函数,我认为问题是我没有在每次插入节点时正确地更新高度。该程序可以很好地处理单次旋转,但双次旋转不起作用。任何帮助都将不胜感激。

您必须检查并平衡节点插入点上方的所有树级别。