开发者

What is the correct implementation of AVL Tree Rotation?

开发者 https://www.devze.com 2023-02-15 04:03 出处:网络
When inserting 50,49,48 into an AVL Tree, it prints out. The root is: 50 50 Level: 0 Height: 0 49 Level: 1 Height: 0

When inserting 50,49,48 into an AVL Tree, it prints out.

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?

Here are my functions. Rotate Left:

void AVLTree::rotateLeft(AVLNode* node)
{   
    AVLNode* otherNode = 开发者_如何学JAVAnode;


    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;

}

insert:

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


The node parameter to your rotateLeft function is a local variable in rotateLeft. In other words, when you assign a value to that variable in rotateLeft, the n variable in insert is not modified. You need to pass n to rotateLeft either through a pointer or through a reference, i.e. either

void AVLTree::rotateLeft(AVLNode** node)

or

void AVLTree::rotateLeft(AVLNode*& node)

The same principle applies to insert's n parameter - if you want a function to modify the value of a variable, you need to pass it a pointer or reference to that variable rather than its value.

0

精彩评论

暂无评论...
验证码 换一张
取 消