为什么以下代码显示错误?

时间:2014-08-28 11:42:59

标签: c memory-management tree segmentation-fault binary-tree

int count(struct node *root,struct node *p,struct node *q)
{
    if(!root)
    return 0;
    int matches=count(root->left,p,q)+count(root->right,p,q);
    if(root->data==p->data||root->data==q->data)
         return 1+matches;
    else
         return matches;
}
struct node *lca(struct node *root,struct node *p,struct node *q)
{
    if(!root||!p||!q)
    return 0;
    int totalmatches=count(root->left,p,q);
    if(totalmatches==1)
        return root;
    else if(totalmatches==2)
        return lca(root->left,p,q);
    else
        return lca(root->right,p,q);
}
int main()
{
    struct node *root        = newNode(20);
    root->left               = newNode(8);
    root->right              = newNode(22);
    root->left->left         = newNode(4);
    root->left->right        = newNode(12);
    root->left->right->left  = newNode(10);
    root->left->right->right = newNode(14);
    struct node *p=newNode(8);
    struct node *q=newNode(14);
    struct node *t = lca(root, p, q);
    printf("LCA of %d and %d is %d \n", p->data, q->data, t->data);
return 0;

}

以上代码打印BST的最低共同祖先。除了这种情况外,它适用于所有情况。显示的错误是分段错误。

enter image description here

1 个答案:

答案 0 :(得分:0)

在这种情况下,您使用空指针调用lca

lca(20) --> count(left) == 2, so go left
lca(8) --> count(left) == 0, so go right
lca(12) --> count(left) == 0, so go right
lca(14) --> count(left) == 0, so go right
lca(NULL) boom