求最近公共祖先和所有祖先
阿新 • • 發佈:2019-01-28
#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)//求x和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;//等價於left!=NULL && right==NULL
else
return right;//等價於left==NULL && right!=NULL或者left==NULL && right==NULL
}
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;
}