用于在二叉树中查找(有序)节点后继的代码中的分段错误
Segmentation fault in code for finding (inorder) successor of nodes in binary tree
我试图 find/print 二叉树中每个节点的中序后继,但编译器给我 分段错误 作为结果。
结构如下:-
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
.
这是我为 printing/finding 继任者编写的代码:
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);
每当 xptr
是 null
时,控制进入 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);
我试图 find/print 二叉树中每个节点的中序后继,但编译器给我 分段错误 作为结果。
结构如下:-
struct node
{
int x;
struct node *left;
struct node *right;
};
初始条件:
I've passed root of the tree as
a
(insucc()
) andNULL
pointer asb
.
这是我为 printing/finding 继任者编写的代码:
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);
每当 xptr
是 null
时,控制进入 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);