[英]Segmentation fault in code for finding (inorder) successor of nodes in binary tree
我試圖在二叉樹中找到/打印每個節點的inorder后繼,但編譯器給出了分段錯誤作為結果。
這是結構: -
struct node
{
int x;
struct node *left;
struct node *right;
};
初始條件:
我通過樹的根作為
a
(在succ()
和NULL
指針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);
每當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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.