【问题标题】:Why is the following code showing error?为什么下面的代码显示错误?
【发布时间】:2014-10-22 06:23:29
【问题描述】:
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 的最低共同祖先。除了这种情况外,它适用于所有情况。显示的错误是分段错误。

【问题讨论】:

  • 能看到newNode函数吗?
  • 你试过调试吗?
  • 你有一个testcase反复产生segfault,找不到bug?
  • @MattMcNabb 没试过
  • 请尝试调试。你会找到原因的。

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


【解决方案1】:

在这种情况下,您使用空指针调用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

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多