繁体   English   中英

代码中的分段错误,用于查找(顺序)二叉树中节点的后继

[英]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);

每当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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM