【发布时间】: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