找p结点和q结点的共同祖先

算法

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值