c - 二叉搜索树节点始终为 NULL

标签 c binary-tree binary-search-tree

我知道这可能看起来很简单,但在过去的几个小时里我一直在摸不着头脑,试图弄清楚为什么无论我做什么,thisNode 总是 NULL。因为这是 null,这意味着实际上没有任何内容最终添加到树中。大家有什么想法吗?啊啊啊

struct node *tra(struct node * start, Type input) 
{
    struct node * thisNode = start;

    if (thisNode == NULL)
        return thisNode;
    else 
    {
        Type current = thisNode -> el;

        if (strcmp(input, current) > 0)
            return tra(thisNode -> right, input);
        else if (strcmp(input, current) < 0)
            return tra(thisNode -> left, input);
        else
        return thisNode;
    }
}

Ta insert(Type input, Ta ta) 
{
    if ((find(input, ta)) == FALSE) 
    {
        struct node *newEl = tra(ta -> head, input);
        newEl = (struct node*)malloc(sizeof(struct node));
        newEl -> el = input;
        newEl -> left = NULL;
        newEl -> right = NULL;
    }

    return ta;
}

Boolean find(Type input, Ta ta) 
{
    if (tra(ta -> head, input) == NULL)
        return FALSE;
    else
        return TRUE;
}

最佳答案

问题是这样的:

        struct node *newEl = tra(ta -> head, input);
        newEl = (struct node*)malloc(sizeof(struct node));

您分配了新节点,但指针 newEl 丢失了。您的函数 tra 应该返回一个指向该指针的指针,以便让插入函数修改您将新创建的节点附加到的节点。

关于c - 二叉搜索树节点始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926949/

相关文章:

C 连接字符串额外空格

c - spoj 阶乘(超过时间限制错误)。我怎样才能改进我的解决方案?

c - GDB 和 LLDB 都无法在简单的 C 文件中可靠地执行断点命令

ocaml - 二叉树广度优先搜索

c++ - BST不断出现段错误

c++ - std::stringstream 类需要有 dll 接口(interface)

math - Big O(logn) 是以 e 为底的对数吗?

c++ - 将二叉树保存到文件

javascript - 二叉搜索树添加方法不对每个输入进行排序 - JavaScript

c++ - 悬挂指针 - 请验证