[英]Segmentation fault in code for finding (inorder) successor of nodes in binary tree
I was trying to find/print the inorder successor of each node in a binary tree but the compiler is giving me segmentation fault as the result. 我试图在二叉树中找到/打印每个节点的inorder后继,但编译器给出了分段错误作为结果。
Here is the structure:- 这是结构: -
struct node
{
int x;
struct node *left;
struct node *right;
};
Initial condition: 初始条件:
I've passed root of the tree as
a
(insucc()
) andNULL
pointer asb
.我通过树的根作为
a
(在succ()
和NULL
指针b
。
Here is my code for printing/finding the successor: 这是我打印/寻找后继者的代码:
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;
}
I've tested the rest of the code (building the tree) and it is working fine. 我已经测试了其余的代码(构建树),它运行正常。
Consider this snippet: 请考虑以下代码段:
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);
whenever the xptr
is null
, control enters else
part and then tries to print xptr->x
which is de-referencing a null pointer ( null->x
). 每当
xptr
为null
,控制进入else
部分,然后尝试打印xptr->x
,它取消引用空指针 ( null->x
)。 Hence the segmentation fault. 因此分段错误。
I think you wrote this by mistake: 我想你错误地写了这个:
printf("%d is the successor of no one\n",xptr->x);
which in my opinion should be: 在我看来应该是:
printf("%d is the successor of no one\n",a->x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.