#include "btree.cpp"
#include<iostream>
using namespace std;
bool allAncestor(BTNode *b, ElemType t)
{
if (b == NULL)
return false;
else if ((b->lchild != NULL && b->lchild->data == t) || (b->rchild != NULL && b->rchild->data == t))
{
cout<< b->data<<" ";
return true;
}
else if (allAncestor(b->lchild, t) || allAncestor(b->rchild, t))
{
cout<< b->data<<" ";
return true;
}
else
return false;
}
BTNode *nearestAncestor(BTNode *b,ElemType x,ElemType y)
{
if(b==NULL || b->data==x || b->data==y)
return b;
BTNode *left=nearestAncestor(b->lchild,x,y);
BTNode *right=nearestAncestor(b->rchild,x,y);
if(left!=NULL && right!=NULL)
return b;
else if(left!=NULL)
return left;
else
return right;
}
int main()
{
BTNode *b;
ElemType x = 'F', y = 'H';
CreateBTNode(b,"A(B(D,E),C(F,G(,H)))");
cout<<"二叉树b为:";DispBTNode(b);cout<<endl;
cout<<"结点"<<x<<"和"<<y<<"的最近公共祖先为:"<<nearestAncestor(b,x,y)->data<<endl;
cout<<"结点"<<y<<"的所有祖先为:";allAncestor(b, y);cout<<endl;
return 0;
}