二叉树查找公共祖先
#include <iostream>
//#include <climits>
using namespace std;
#define MAXNUM 50
typedef int Elemtype;
typedef struct BiTNode
{
Elemtype data;
struct BiTNode *lchild;
struct BiTNode *rchild;
}BiTNode,*BiTree;
typedef struct
{
BiTree bt;
int tag; // 标签
}Elem;
typedef struct sqStack // 栈
{
Elem s_elem[MAXNUM];
int top;
}sqStack;
void InitStack(sqStack &s) // 初始化栈
{
s.top=-1;
}
bool IsEmpty(sqStack s) // 判断栈是否为空
{
if (s.top==-1)
return true;
else
return false;
}
bool Push(sqStack &s,Elem e) // 进栈
{
if ((s.top+1)==MAXNUM) // 栈满
return false;
s.s_elem[++s.top]=e;
return true;
}
bool Pop(sqStack &s,Elem &e) // 出栈
{
if (s.top==-1) // 栈满
return false;
e=s.s_elem[s.top--];
return true;
}
bool GetTop(sqStack s,Elem &e) // 获取栈顶元素
{
if (s.top==-1) // 栈满
return false;
e=s.s_elem[s.top];
return true;
}
void CreateBiTree(BiTree &T)
{
Elemtype data;
scanf("%d",&data);
if(data!=99)
{
T=new BiTNode;
T->data=data;
T->lchild=NULL;
T->rchild=NULL;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int CommonAncestor(BiTree T,Elemtype x,Elemtype y)
{
sqStack s;
Elemtype xe[MAXNUM]={0},ye[MAXNUM]={0};
int find_sign=0; // 如果find_sign=2,证明xy的祖先都进入xe和ye数组中
InitStack(s);
BiTNode *p=T; // 指向头结点
do
{
while (p)
{
Elem et;
et.bt=p;
et.tag=1;
Push(s,et);
p=p->lchild; // 将左孩子全部进栈
}
if (!IsEmpty(s))
{
Elem ee;
Pop(s,ee);
if (ee.tag==1){
ee.tag=2;
p=ee.bt->rchild;
Push(s,ee);
}
else{
//cout<<ee.bt->data<<" ";
if (ee.bt->data==x)
{
for (int i=0;i<=s.top;++i)
{
xe[i]=s.s_elem[i].bt->data;
}
xe[s.top+1]=ee.bt->data;
find_sign++;
}
else if (ee.bt->data==y)
{
for (int i=0;i<=s.top;++i)
{
ye[i]=s.s_elem[i].bt->data;
}
ye[s.top+1]=ee.bt->data;
find_sign++;
}
if (find_sign==2) // x和y的祖先都在xe和ye数组内
{
int i=0;
int common_ancestor=-1;
while (xe[i]!=0&&ye[i]!=0)
{
if (xe[i]==ye[i])
{
common_ancestor=xe[i];
}
++i;
}
return common_ancestor;
}
}
}
} while (!IsEmpty(s));
return -1;
}