【发布时间】:2017-10-12 04:26:33
【问题描述】:
我使用递归尝试了以下算法,但节点没有附加到树上。请告诉我有什么问题。
void search_add(struct node *t)
{
if(t==NULL)
{
t = newNode(temp->key);
return;
}
else if(t->key>temp->key)
{
search_add(t->right);
}
else if (t->key<temp->key)
{
search_add(t->left);
}
}
void insert(struct node *node, int key)
{
temp = newNode(key);
search_add(node);
}
int main(void)
{
root = newNode(50);
insert(root,30);
return 0;
}
【问题讨论】:
-
t = newNode(temp->key);只是更改传递的本地副本,然后被遗忘,调用者的t->right或t->left仍然是NULL。 -
此网站上有 数千个 重复此问题。不幸的是,错误通常是由初学者犯的,问题的标题/文本如此不同,他们很难真正找到。
t = newNode(temp->key);对传入的 调用者 参数执行 nothing。就函数而言,它是一个局部变量。所有这些最终都会导致内存泄漏。 Example duplicate here. -
欢迎来到 StackOverflow。请采取tour,学习提出好问题stackoverflow.com/help/how-to-ask,制作minimal reproducible example。如果您正在寻求有关调试代码的帮助,请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs
-
temp 是一个全局变量。
-
@WhozCraig,我该如何解决?
标签: c pointers recursion data-structures binary-search-tree