2014-08-28 65 views
-1
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

+0

我们可以看到newNode函数吗? – Igor 2014-08-28 11:45:55

+1

您是否尝试过调试? – 2014-08-28 11:48:41

+0

你有一个反复产生段错误的测试用例,你找不到错误? – 2014-08-28 11:50:44

回答

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 
相关问题