我正在编写一个程序来查找二叉树(不是 BST)中最近的祖先。我找到了一个示例工作代码:
mynode *closestAncestor(mynode* root, mynode* p, mynode* q)
{
mynode *l, *r, *tmp;
if(root == NULL)
{
return(NULL);
}
if(root->left==p || root->right==p || root->left==q || root->right==q)
{
return(root);
}
else
{
l = closestAncestor(root->left, p, q);
r = closestAncestor(root->right, p, q);
if(l!=NULL && r!=NULL)
{
return(root);
}
else
{
tmp = (l!=NULL) ? l : r;
return(tmp);
}
}
}
我正在尝试执行以下操作(仅传递数据值并仅查找祖先的数据值,而不关心其指针)
int closestanc(node * root, int n1, int n2)
{
int l, r;
if(root == NULL)
return -1;
if(root->right->data == n1 || root->right->data == n2 || root->left->data == n1 || root->left->data == n2)
return root->data;
else
{
l = closestanc(root->left, n1, n2);
r = closestanc(root->right, n1, n2);
if(l!= -1 && r!= -1)
return root->data;
else
return (l != -1 ? l : r);
}
}