二叉搜索树的最近公共祖先(C++)

#include<iostream>
using namespace std;
class Node{
	public:
	int d,w,K;
	Node*l,*r;
	Node(){
		l=NULL;r=NULL;
		d=0;
	}
	Node(int a){
		l=NULL;r=NULL;
		d=a;
	}
};
class Tree{
	int *k,*in,n,m,pos,pa,x,y,deep,dpt,K;
	Node *root;

	bool isTree(Node *r){

	}

	public:
		Tree(){
	        cin>>m>>n;
			pos=0;
			k=new int[n];
			in=new int[n];
			int i,j,a;
			for(i=0;i<n;i++){
		     	cin>>k[i];
				in[i]=k[i];
			}
			for(i=0;i<n;i++)
			for(j=0;j<n-1-i;j++){
				if(in[j]>in[j+1]){
					a=in[j];
					in[j]=in[j+1];
					in[j+1]=a;
				}
			}
			Create(root,0,n-1,0,n-1);
			//Print(root);
			//cout<<endl;
			while(m--){
				K=0;
				deep=1;
				dpt=0;
				cin>>x>>y;
				int a=0,b=0;
				for(i=0;i<n;i++){
					if(k[i]==x)
					a=1;
					if(k[i]==y)
					b=1;
				}
				if(a==0&&b==1){
				cout<<"ERROR: "<<x<<" is not found."<<endl;
					continue;
				}
				else if(a==1&&b==0){
				cout<<"ERROR: "<<y<<" is not found."<<endl;
				continue;
				}else if(a==0&&b==0){
				cout<<"ERROR: "<<x<<" and "<<y<<" are not found."<<endl;
					continue;
				}else
				{
					int pa=Find(x,y,root);
					if(pa==x)
					cout<<x<<" is an ancestor of "<<y<<"."<<endl;
					else
					if(pa==y)
					cout<<y<<" is an ancestor of "<<x<<"."<<endl;
					else
					cout<<"LCA of "<<x<<" and "<<y<<" is "<<pa<<"."<<endl;



				}
			}
		}
		void Create(Node*&t,int s1,int e1,int s2,int e2){
			if(s1<=e1){
				t=new Node(k[s1]);
				int i;
				for(i=s2;i<e2;i++)
				if(in[i]==k[s1])
				break;
				Create(t->l,s1+1,s1+(i-s2),s2,i-1);
				Create(t->r,s1+1+(i-s2),e1,i+1,e2);
			}
		}
		int Find(int a,int b,Node *r){
			if(a>r->d&&b>r->d)
			return Find(a,b,r->r);
			else
			if(a<r->d&&b<r->d)
			return Find(a,b,r->l);
			else return r->d;

		}
		void Print(Node*r){
			if(r->l)
			Print(r->l);
			cout<<r->d<<" ";
			if(r->r)
			Print(r->r);
		}
};
int  main(){
	int t,n,m,i,j;
	char ch;
	Tree tree;

	return 0;
}

 

 

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草海桐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值