AVL树旋转的正确实现是什么?

时间:2011-03-07 20:14:23

标签: c++ avl-tree

将50,49,48插入AVL树时,会打印出来。

The root is: 50 
50 Level: 0 Height: 0

 49 Level: 1 Height: 0
50 Level: 0 Height: -1

50 Level: 0 Height: 0 -->> Rotation did not work?

这是我的功能。 向左旋转:

void AVLTree::rotateLeft(AVLNode* node)
{   
    AVLNode* otherNode = node;


    otherNode = node->leftchild;
    node->leftchild = otherNode->rightchild;
    otherNode->rightchild = node;

    node->height = max( height(node->leftchild), height(node->rightchild)) +1;
    otherNode->height = max( height(otherNode->leftchild) , height(otherNode->rightchild))+1;
    node = otherNode;

}

插入:

AVLTree::AVLNode* AVLTree::insert(int d,AVLNode *n){
if (n == NULL)
{
    n = new AVLNode;
    n->data = d;
    n->leftchild = NULL;
    n->rightchild = NULL;
    n->height = 0;

} else if( d < n->data) {

    n->leftchild = insert(d,n->leftchild);

    if (height(n->leftchild) - height(n->rightchild) == 2) {
        if (d < n->leftchild->data) {
            rotateLeft(n);
        } else {
            rotateLeftTwice(n);
        }
    }

} else if (d > n->data) {

    n->rightchild = insert(d,n->rightchild);

    if (height(n->rightchild) - height(n->leftchild) == 2) {
        if (d > n->rightchild->data) {
            rotateRight(n);
        } else {
            rotateRightTwice(n);
        }
    }
} else {    
    ;
}
n->height = max(height(n->leftchild), height(n->rightchild))+1;
return n;}

1 个答案:

答案 0 :(得分:1)

node函数的rotateLeft参数是rotateLeft中的局部变量。 换句话说,当您在rotateLeft中为该变量指定值时,n中的insert变量不会被修改。您需要通过指针或引用将n传递给rotateLeft,即 任

void AVLTree::rotateLeft(AVLNode** node)

void AVLTree::rotateLeft(AVLNode*& node)

同样的原则适用于insert的{​​{1}}参数 - 如果你想要一个函数来修改变量的值,你需要传递一个指针或对该变量的引用而不是它的值。