BST program in C



请帮我。我总是犯seg错误!我想使用递归来创建和插入一个新节点。请帮我调试这个。

//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 foundn");
}
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;
}

为什么我总是犯seg错误。有人能给我解释一下吗?我在做不该做的事吗?还是我在某个时候失踪了?

学习使用调试器!

通过主函数,您会看到root的值在每次调用createTree 后都会保持为NULL

createTree函数不修改root的值,而只是修改root值的副本。

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

树的根没有分配到任何位置;在你的函数createTree中,你可能认为它被分配在:中

if (curr == NULL)
    curr = newnode;

但是CCD_ 10对于函数是局部的,并且不影响CCD_。您需要将参数curr更改为指向指针的指针,否则该函数不适用于分配根节点或子节点。树的根没有分配到任何位置;在你的函数createTree中,你可能认为它被分配在:中

if (curr == NULL)
    curr = newnode;

但是curr是函数的局部,即使您将其作为参数curr,也不会影响root。您需要将参数curr更改为指向指针的指针,否则该函数不适用于分配根节点或子节点。也就是说,函数声明变为:

void createTree(struct Tree **curr, int val)

当然,您必须相应地更改函数内curr的使用(即,指向的地址是*curr,而它以前是curr),函数的调用需要传递指针的地址,而不是值(例如,createTree(&root, arr[i]))。

edit:或者,实际上,让函数返回curr,并始终将返回值分配给调用createTree的每个位置的相关指针,这要感谢@JonathanLeffler的观察。

最新更新