简体   繁体   English

分割错误,c中的二进制搜索树

[英]Segmentation fault, binary search tree in c

I want to insert data to the tree using this function: 我想使用此功能将数据插入树中:

struct treeNode{
    data* val;
    struct treeNode *left, *right, *parent;
};


void insert(data *d, struct treeNode **leaf, struct treeNode **leaf_par)
{
    if( *leaf == 0 )
    {
        *leaf = (struct treeNode*) malloc( sizeof( struct treeNode ) );
        (*leaf)->val = d;
        /* initialize the children to null */
        (*leaf)->left = 0;
        (*leaf)->right = 0;
        /* initialize the parent */
        (*leaf)->parent = *leaf_par;  //here I receive segmentation fault
    }
    else if(strcmp(d->name, (*leaf)->val->name) < 0)
    {
        insert( d, &(*leaf)->left, &(*leaf) );
    }
    else if(strcmp(d->name, (*leaf)->val->name) > 0)
    {
        insert( d, &(*leaf)->right, &(*leaf) );
    }
}

In main I have: 我主要有:

struct treeNode *root = NULL;
data d1 = {"Smith"};
insert(&d1, &root, NULL);

Segmentation fault is there: 细分错误存在:

(*leaf)->parent = *leaf_par;

At first time *leaf_par is NULL and I don't know why it's not running correctly. 第一次* leaf_par为NULL,我不知道为什么它不能正确运行。 How should I fix my insert function? 我应该如何修复插入功能? Without "parent" pointer it's easy, but I have to do that with "parent" and it's not working. 没有“父”指针,这很容易,但是我必须使用“父”指针来做,而且它不起作用。

You are trying to dereference NULL; 您正在尝试取消引用NULL。 don't do that. 不要那样做

A simple fix for your first insert is: 一个简单的解决方法是:

insert(&d1, &root, &root);

Deeper inserts into the recursion will fix the pointer. 递归的更深层插入将修复指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM