运行函数时可执行崩溃

时间:2019-03-16 00:03:49

标签: c avl-tree

我正在为分配创建AVL,但是每当我调用向右旋转和向左旋转功能时,可执行文件都会崩溃,而不会出现错误消息。我认为这可能是由于NULL指针异常引起的,但我不确定。

这是我的轮换代码:

TNODE *rotate_right(TNODE *y){

TNODE *x=y->left;
TNODE *t2=x->right;

x->right=y;
y->left=t2;

y->height =max(height(y->left),height(y->right))+1;
x->height=max(height(x->left),height(x->right))+1;
}

TNODE *rotate_left(TNODE *x){
TNODE *y=x->right;
TNODE *t2=y->left;

y->left=x;
x->right=t2;

y->height =max(height(y->left),height(y->right))+1;
x->height=max(height(x->left),height(x->right))+1;
}

这是我在其中调用它们的插入函数:

void insert(TNODE **rootp, char *name, float score){
    TNODE *np = (TNODE *) malloc(sizeof(TNODE));
    if (np == NULL) return;
    strcpy(np->data.name, name);
    np->data.score = score;
    np->height = 1;
    np->left = NULL;
    np->right = NULL;

    // 1. Perform the normal BST insertion
    if (*rootp == NULL) {
        *rootp = np;
         return;
    }

    TNODE *root = *rootp;
    if (strcmp(name, root->data.name) < 0 ){
       insert(&root->left, name, score);
    }
    else if (strcmp(name, root->data.name) > 0 ){
       insert(&root->right, name, score);
    }
    else return ;

    // 2. update height of this root node

    // add your code here
    root->height=height(root);

    // STEP 3: get the balance factor of this root node


    // add your code here
    int balance=balance_factor(root);

    // STEP 4: re-balance if not balanced

    // add your code here

   if(balance>1&&balance_factor(root->left)>=0){
       rotate_right(root);
   }
   else if(balance>1&&balance_factor(root->left)<0){
       rotate_left(root->left);
       rotate_right(root);
   }
   else if(balance<-1&&balance_factor(root->right)>=0){
       rotate_left(root);
   }
   else if(balance<-1&&balance_factor(root->right)<0){
       rotate_right(root->right);
       rotate_left(root);
   }

 }

如果我注释掉我必须旋转的最后一部分,则代码可以正常运行,因此我很确定问题出在那。预先感谢您的帮助。

0 个答案:

没有答案
相关问题