繁体   English   中英

二进制搜索树插入(C)

[英]Binary search tree insertion (C)

谢谢,由于某种原因,它无法正常工作。 当我运行程序时,它仅给出错误“ 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);
}

你有

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

if条件永远不会为真,就像rNULL ,循环将结束,而不会从函数中返回任何内容。

如果您未进入while循环或不返回while退出了while循环,将会发生什么? 它不会返回任何内容,并且行为是不确定的。

因此,返回NULL以指示未找到,或者将if(r==NULL)移出循环。 它不会在循环内执行。

暂无
暂无

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

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