2

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

1 に答える 1

1

関数のnodeパラメーターrotateLeftは のローカル変数ですrotateLeft。つまり、 の変数に値を割り当ててもrotateLeft、 のn変数insertは変更されません。ポインターまたは参照を介してn渡す必要があります。rotateLeft

void AVLTree::rotateLeft(AVLNode** node)

また

void AVLTree::rotateLeft(AVLNode*& node)

insertのパラメータにも同じ原則が適用されnます。関数で変数の値を変更する場合は、その値ではなく、その変数へのポインタまたは参照を渡す必要があります。

于 2011-03-07T20:50:54.450 に答える