c - BST - 递归插入

标签 c data-structures

我已经为 BST 编写了一个递归插入算法。但是,该算法存在一个错误。如果有人可以给我一个指示,将不胜感激。请注意初始调用中的 y = NULL

    void insert_recursive(Node **root, Node *z, Node *y) {
    // z is the pointer to the node being inserted, and y keeps track of z's parent
    Node *x = *root;

    if (x != NULL) {
        y = x;
        if (z->val < x->val)
            insert_recursive(&(x->left), z, y);
        else
            insert_recursive(&(x->right), z, y);
    }
    else {
        if (y == NULL)
            { *r = z; printf("inserting root, %d\n", z->val); }
        else if (z->val < x->val)
             { y->left = z; printf("inserting left of %d, item %d\n", y->val, z->val); }
        else
            { y->right = z; printf("inserting right of %d, item %d\n", y->val, z->val); }
    }
} 

最佳答案

这可能不是唯一的问题,而是你的问题

else if (z->val < x->val)

出现在 if (x != NULL)else 子句中。换句话说,x在这里保证为NULL。

关于c - BST - 递归插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10467543/

相关文章:

c++ - 为项目构建大型库时的最佳实践

data-structures - 为什么我们需要一个单独的数据结构(例如B-Tree)用于数据库和文件系统?

python - Python 中从嵌套元组到二项式树的边缘

c++ - STL priority_queue 的效率

java - 如何读取CSV文件并对数据进行操作?

无法在我自己的代码中使用 CHOLMOD 和 CUDA 加速

c 链式困惑

algorithm - 将不同的事件计数为子序列

Pro*c语言创建序列

c - C 程序中第一个 scanf 行出现段错误