gpt4 book ai didi

c - C 中的 BST 程序

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:28 24 4
gpt4 key购买 nike

请帮我解决这个问题。我不断遇到段错误!我想使用递归来创建和插入一个新节点。请帮我调试一下。

//Create a Binary Search Tree From an array.
struct Tree
{
int data;
struct Tree *lchild;
struct Tree *rchild;
};
struct Tree *root = NULL;
struct Tree *node(int val)
{
struct Tree *tempnode;
tempnode = (struct Tree*)malloc(sizeof(struct Tree));
tempnode->data = val;
tempnode->rchild = NULL;
tempnode->lchild = NULL;
return tempnode;
}

void createTree(struct Tree *curr, int val)
{
struct Tree *newnode = node(val);

if (curr == NULL)
curr = newnode;
else if(val < curr->data)
{
createTree(curr->lchild,val);
}
else if(val > curr->data)
{
createTree(curr->rchild,val);

}
else
printf("Error Similar data found\n");
}

void inorder(struct Tree *root)
{
if (root->lchild != NULL)
inorder(root->lchild);
printf("[%d] ",root->data);
if (root->rchild != NULL)
inorder(root->rchild);
}
int main()
{
// root = NULL;
int i = 0, arr[5] = {41,12,32,23,17};
for(i;i<5;i++)
createTree(root,arr[i]);
inorder(root);
return 0;
}

为什么我总是遇到段错误。有人可以解释一下吗?我在做不该做的事吗?还是我在某个时候失踪了?

最佳答案

学习使用调试器!

单步执行 main 函数,您会发现每次调用 createTree 后,root 的值将保持为 NULL。 p>

createTree 函数并未修改root 的值,而只是修改了root 值的副本。

您的createTree 函数需要一个struct Tree **curr,一个指向指针的指针。这允许函数修改原始值,而不是本地副本。

关于c - C 中的 BST 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20078854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com