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.
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
.
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
). 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.