gpt4 book ai didi

c - 用于在二叉树中查找(有序)节点后继的代码中的段错误

转载 作者:行者123 更新时间:2023-12-01 12:32:45 26 4
gpt4 key购买 nike

我试图在二叉树中查找/打印每个节点的中序后继,但编译器给我的结果是段错误

这是结构:-

struct node
{
int x;
struct node *left;
struct node *right;
};

初始条件:

I've passed root of the tree as a (in succ()) and NULL pointer as b.

这是我用于打印/查找继任者的代码:

struct node *(succ(struct node *a,struct node *b))
{
struct node *xptr;
xptr=b;
if(a!=NULL)
{
xptr=succ(a->left,xptr);
if(xptr!=NULL)
{
printf(" %d is the successor of %d\n",a->x,xptr->x);
}
else
printf("%d is the successor of no one\n",xptr->x);
xptr=a;
if(xptr->right==NULL)
{
return xptr;
}
xptr=succ(a->right,xptr);
return xptr;
}
else
return xptr;
}

我已经测试了其余代码(构建树)并且它工作正常。

最佳答案

考虑这个片段:

if(xptr!=NULL)          
{
printf(" %d is the successor of %d\n",a->x,xptr->x);
}
else
printf("%d is the scuccessor of no one\n",xptr->x);

每当 xptrnull 时,控制进入 else 部分,然后尝试打印 xptr->x这是取消引用空指针(null->x)。因此出现段错误。

我认为你写错了:

printf("%d is the successor of no one\n",xptr->x);

我认为应该是:

printf("%d is the successor of no one\n",a->x);

关于c - 用于在二叉树中查找(有序)节点后继的代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32090121/

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