简体   繁体   English

二进制搜索树插入(C)

[英]Binary search tree insertion (C)

Thanks, now for some reason it's not working as intended. 谢谢,由于某种原因,它无法正常工作。 When I run the program it just gives an error "bst.exe has stopped working" and it happens in this function. 当我运行程序时,它仅给出错误“ bst.exe已停止工作”,并且它发生在此函数中。

static NODE *insert_i(NODE *r, int x)
{
    NODE *leaf;

    while(r)
    {
        if(r->val == x)
            return r;

        if(x < r->val && r->left != NULL)
            r = r->left;

        else if(x > r->val && r->right != NULL)
            r = r->right;
    }

    leaf = malloc(sizeof(NODE));
    leaf->left = NULL;
    leaf->right = NULL;
    leaf->val = x;
    count++;

    if(x < r->val)
        r->left = leaf;

    else
        r->right = leaf;

    return r;
}


void bst_insert(BST_PTR t, int x)
{
    t->root = insert_i(t->root, x);
}

You have 你有

while(r)
{
    if(r == NULL)

The if condition will never be true, as if r is NULL then the loop will end, without returning anything from the function. if条件永远不会为真,就像rNULL ,循环将结束,而不会从函数中返回任何内容。

What will happen if you while loop is not entered or exited without returning? 如果您未进入while循环或不返回while退出了while循环,将会发生什么? It will not return anything and behaviour will be undefined. 它不会返回任何内容,并且行为是不确定的。

So, return NULL to indicate that not found or move if(r==NULL) out of the loop. 因此,返回NULL以指示未找到,或者将if(r==NULL)移出循环。 It will not be executed inside the loop. 它不会在循环内执行。

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

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