我知道这可能看起来很简单,但在过去的几个小时里我一直在摸不着头脑,试图弄清楚为什么无论我做什么,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/