AVL树双旋转错误

时间:2016-05-11 05:09:15

标签: c++ nodes avl-tree

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

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

以下是我的插入功能:

   let mainStoryboard = UIStoryboard(name: "Storyboard", bundle:  NSBundle.mainBundle())
    let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MyController") as UIViewController
    self.presentViewController(vc, animated: true, completion: nil)

    <<wait for some seconds>>

    -->> dismissview from parents view ???

这是我迄今为止提出的功能,为我的项目提供了balance功能,以及我将在这里提供的updateHeight:

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;
}

对于更新高度:

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;

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

5,8,9,3,6,7,5

我的输出是这样的:

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

应该是:

      8
     / \
    5   9
   / \
  3   6
 /     \
2       7

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

1 个答案:

答案 0 :(得分:0)

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