算法
BiTree a[100];
BiTree b[100];
int s=0;
/*
采用后序遍历算法,当找到p结点时,栈a里的所有元素就是p的祖先,当找到q结点时,
栈b里全是q结点的祖先,对两个栈从栈底到栈顶进行匹配,即可找到最近的共同祖先
*/
BiTree Ancestor(BiTree T, BiTree p, BiTree q){
int flag=0;
BiTree temp = (BiTree)malloc(sizeof(BiNode));
a[s]=T;
while(s!=-1){
if(a[s]->lchild&&a[s]->lchild!=temp&&a[s]->rchild!=temp){
a[s+1]=a[s]->lchild;
s++;
}
else if(a[s]->rchild&&temp!=a[s]->rchild){
a[s+1]=a[s]->rchild;
s++;
}
else{
temp=a[s--];
if(temp == p || temp == q){
if(flag==0){
flag = 1;
for(int i=0; i<=s; i++){
b[i] = a[i];
}
}
else s=-1;
}
}
}
int j;
for(j=0; a[j] == b[j]; j++);
return a[j-1];
}
测试环境
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxsize 100
#define ElemType char
//二叉树的创建序列
//ab#df###c#e##
//abd##e##cf###
//ab#df###c#e##
typedef struct BiNode{
ElemType date;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
BiNode* CreateBiTree();
void Traverse(BiNode *p);
void DeleteTree(BiTree &t);
BiTree Ancestor(BiTree T, BiTree p, BiTree q);
int main(){
BiTree t = CreateBiTree();
BiTree p,q;
p = t->lchild->rchild;
q = t->lchild->lchild;
printf("%c\n",p->date);
printf("%c\n",q->date);
BiTree f = Ancestor(t, p, q);
printf("%c",f->date);
DeleteTree(t);
return 0;
}
BiTree a[100];
BiTree b[100];
int s=0;
/*
采用后序遍历算法,当找到p结点时,栈a里的所有元素就是p的祖先,当找到q结点时,
栈b里全是q结点的祖先,对两个栈从栈底到栈顶进行匹配,即可找到最近的共同祖先
*/
BiTree Ancestor(BiTree T, BiTree p, BiTree q){
int flag=0;
BiTree temp = (BiTree)malloc(sizeof(BiNode));
a[s]=T;
while(s!=-1){
if(a[s]->lchild&&a[s]->lchild!=temp&&a[s]->rchild!=temp){
a[s+1]=a[s]->lchild;
s++;
}
else if(a[s]->rchild&&temp!=a[s]->rchild){
a[s+1]=a[s]->rchild;
s++;
}
else{
temp=a[s--];
if(temp == p || temp == q){
if(flag==0){
flag = 1;
for(int i=0; i<=s; i++){
b[i] = a[i];
}
}
else s=-1;
}
}
}
int j;
for(j=0; a[j] == b[j]; j++);
return a[j-1];
}
//用C++引用的方法删除树中所有节点
void DeleteTree(BiTree &t){
if(t){
DeleteTree(t->lchild);
DeleteTree(t->rchild);
delete t;
t = NULL;
}
}
//用递归方法以中序遍历的方式创建二叉树
BiNode* CreateBiTree(){
BiNode *p;
char a;
scanf("%c",&a);
if(a=='#')
p=NULL;
else{
p=(BiNode *)malloc(sizeof(BiNode));
p->date=a;
p->lchild=CreateBiTree();
p->rchild=CreateBiTree();
}
return p;
}
//递归方法中序遍历二叉树
void Traverse(BiNode *p){
if(p==NULL){
return;
}
else{
printf("%c",p->date);
Traverse(p->lchild);
Traverse(p->rchild);
}
return;
}