c - 二叉搜索树插入(C)

标签 c binary-search-tree

谢谢,现在由于某种原因它没有按预期工作。当我运行该程序时,它只是给出一个错误“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 那么循环就会结束,不从函数返回任何内容。

关于c - 二叉搜索树插入(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20469795/

相关文章:

algorithm - 我关于先序遍历的想法有什么问题

java - 将文件中的奇数和偶数更改为二进制代码

c++ - 从二叉搜索树中删除具有给定值的节点的函数

c - 是否有必要在读取二叉搜索树中的第一个值时重新分配 'root' 节点?

c - 可变顺序对 sscanf 重要吗?

c - printf 打印额外的 * 字符

c++ - 访问 BST 子节点时出现段错误。为什么?

c - 这个函数做了什么来帮助它以不同的方式接受输入以及如何执行 for 循环中的条件

c - 通过 union 别名

c - 使用 glTimerFunc 的 GLUT 动画