问题描述:给定一个二叉搜索树的先序遍历,求两个结点的最低公共祖先
解题思路:二叉搜索树的中序遍历为排好序的序列,所以只有先序也可建树;直接根据二叉搜索树的先序序列逐个插入也可建树。最低公共祖先的查找根据高度来判断,和1151 LCA in a Binary Tree (30 分)差不多。也可以看看当初的代码。但有更方便的方法。
AC代码:
#include<iostream>
#include<unordered_map>
#include<algorithm>
#include<unordered_set>
#include<string>
using namespace std;
#define MAX 10005
int pre[MAX],in[MAX],N,M;
typedef struct node{
int left,right;
}node;
unordered_map<int,node>arr;
void CreatBST(int preL,int inL,int inR)
{
if(inL>inR)return ;
int i=inL;
while(pre[preL]!=in[i])++i;
if(i-inL)arr[pre[preL]].left=pre[preL+1];
else arr[pre[preL]].left=0;
if(inR-i)arr[pre[preL]].right=pre[preL+i-inL+1];
else arr[pre[preL]].right=0;
CreatBST(preL+1,inL,i-1);
CreatBST(preL+i-inL+1,i+1,inR);
}
void findLCA(int v,int a,int b)
{
if(a==v)printf("%d is an ancestor of %d.\n",a,b);
else if(b==v)printf("%d is an ancestor of %d.\n",b,a);
else if(a<v&&b>v||a>v&&b<v)printf("LCA of %d and %d is %d.\n",a,b,v);
else if(a<v&&b<v)findLCA(arr[v].left,a,b);
else findLCA(arr[v].right,a,b);
}
int main()
{
//freopen("test.txt","r",stdin);
int i,u,v,root;
scanf("%d %d",&M,&N);
for(i=0;i<N;++i){
scanf("%d",&pre[i]);
if(i==0)root=pre[0];
in[i]=pre[i];
}
sort(in,in+N);
CreatBST(0,0,N-1);
while(M--){
scanf("%d %d",&u,&v);
if(!arr.count(u)&&!arr.count(v))printf("ERROR: %d and %d are not found.\n",u,v);
else if(!arr.count(u)||!arr.count(v))printf("ERROR: %d is not found.\n",arr.count(u)?v:u);
else findLCA(root,u,v);
}
return 0;
}