首页 > 解决方案 > AVL TREE Malloc 插入新节点时的函数

问题描述

我最近在 C 中成功创建了一个 bst。然后我的尝试是创建一个 AVL ..这样做的第一步是在每个节点中添加一个额外的组件 bf(平衡因子)..我按如下方式进行。

    struct tnode{
        int info;
        struct tnode*left;
        struct tnode*right;
        int bf;//new field for avl tree..
                };

每次 malloc 在插入时为新节点分配一个地址...我将其信息部分分配给用户输入的值..将左右指针设置为 NULL.除此之外,它将新节点的 bf 分配给 0..在插入第一个节点(即根节点)程序后,下次在 malloc 部分甚至无法为 newnode 分配内存...一旦我删除了 newnode->bf=0 的部分..问题就消失了。 . 为什么会发生这种情况?. 下面是我的主要函数和 add() 函数,它以整数作为输入并将其插入到树中,根节点作为全局声明的“根”。

    int main(){
    int choice,val;
    deci:
    printf("\n1.Insert");
    printf("\n2.Display");
    printf("\n3.Search.");
    printf("\n4.Delete");
    printf("\n5.Naa..");
    scanf("%d",&choice);
    switch(choice){
            case 1:printf("\nEnter element to add:");
                    scanf("%d",&val);
                    add(val);

                    //display();
                    break;
            case 2:display();
                    break;
            case 3:printf("\nEnter element to search for:");
                    scanf("%d",&val);
                    search(val);
                    break;

            case 4:printf("\nEnter element to Delete: ");
                    scanf("%d",&val);
                    deletei(val);
                    display();
                    break;
            case 5:return 0;

            }
    goto deci;
    return 0;
    }


    void add(int val){
    struct tnode * newnode=(struct tnode * )malloc(sizeof(struct tnode *));
    newnode->info=val;
    newnode->left=newnode->right=NULL;
    newnode->bf=0;//problem making,problem solved removing this statement
    if(root==NULL){
            root=newnode;

                    }                       
    else{
        struct tnode*tree=root;
        struct tnode*ptree=NULL;
    while(tree!=NULL){
                    if(val<tree->info){
                                        ptree=tree;
                                        tree=tree->left;

                    }
                    else{
                        ptree=tree;
                        tree=tree->right;
                    }                       


        }   
    if(val<ptree->info){

                ptree->left=newnode;
                tree=ptree->left;


        }
else{
ptree->right=newnode;   
tree=ptree->right;

    }
    }


    }   

标签: cpointersmallocavl-treenull-pointer

解决方案


您的第一个主要错误是您仅为newnode in的地址分配空间add()。您应该将其转换为:

struct tnode * newnode=(struct tnode * )malloc(sizeof(struct tnode));

在这种情况下,您为所需的节点分配整个空间。

PS。还请退出“goto”指令,因为使用它是一种不好的做法。


推荐阅读