-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的最低共同祖先。除了這種情況,它對所有情況都可以正常工作。顯示的錯誤是分段錯誤。爲什麼下面的代碼顯示錯誤?
我們可以看到newNode函數嗎? – Igor 2014-08-28 11:45:55
您是否嘗試過調試? – 2014-08-28 11:48:41
你有一個反覆產生段錯誤的測試用例,你找不到錯誤? – 2014-08-28 11:50:44