二叉树查找公共祖先

二叉树查找公共祖先

#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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值