给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 LCA)。
输入格式:
输入的第一行给出两个正整数:待查询的结点对数 M(≤ 1 000)和二叉搜索树中结点个数 N(≤ 10 000)。随后一行给出 N 个不同的整数,为二叉搜索树的先序遍历序列。最后 M 行,每行给出一对整数键值 U 和 V。所有键值都在整型int范围内。
输出格式:
对每一对给定的 U 和 V,如果找到 A 是它们的最近公共祖先结点的键值,则在一行中输出 LCA of U and V is A.。但如果 U 和 V 中的一个结点是另一个结点的祖先,则在一行中输出 X is an ancestor of Y.,其中 X 是那个祖先结点的键值,Y 是另一个键值。如果 二叉搜索树中找不到以 U 或 V 为键值的结点,则输出 ERROR: U is not found. 或者 ERROR: V is not found.,或者 ERROR: U and V are not found.。
输入样例:
6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
输出样例:
LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
查找最近公共祖先本身只需要父节点信息,但是父节点信息需要在建树过程中取建立,因此必须建树,建树根据bst的性质和先序序列正常建即可,存树可以使用数组来存,离散化即可,不使用离散化的话可以用链式结构来存树,父节点信息用map或者unordered_map存即可
#include <bits/stdc++.h>
using namespace std;
const int N=10005;
int m,n,a[N],b[N],p,root,l[N],r[N],f[N],st[N],ans;
void add(int u,int x){//向树中插入一个结点
if(x<u){
if(l[u]==-1){
l[u]=x;f[x]=u;
}
else add(l[u],x);
}
else {
if(r[u]==-1){
r[u]=x;f[x]=u;
}
else add(r[u],x);
}
}
void find(int x){
if(st[x]){
ans=x;return;
}
st[x]=1;
if(f[x]!=-1)find(f[x]);
}
int main(){
cin>>m>>n;
for(int i=0;i<n;++i){
cin>>a[i];b[i]=a[i];
}
sort(b,b+n);
memset(l,-1,sizeof l);memset(r,-1,sizeof r);memset(f,-1,sizeof f);
for(int i=0;i<n;++i){
a[i]=lower_bound(b,b+n,a[i])-b;
if(i==0)root=a[i]; //根节点,记录下标
else add(root,a[i]);//非根节点,加到树中
}
while(m--){
int u,v,uu,vv;cin>>u>>v;
uu=lower_bound(b,b+n,u)-b;
vv=lower_bound(b,b+n,v)-b;
if(b[uu]!=u&&b[vv]!=v) printf("ERROR: %d and %d are not found.\n",u,v);
else if(b[uu]!=u) printf("ERROR: %d is not found.\n",u);
else if(b[vv]!=v) printf("ERROR: %d is not found.\n",v);
else {
find(uu);find(vv);
if(ans==uu)printf("%d is an ancestor of %d.\n",u,v);
else if(ans==vv)printf("%d is an ancestor of %d.\n",v,u);
else printf("LCA of %d and %d is %d.\n",u,v,b[ans]);
}
memset(st,0,sizeof st);
}
return 0;
}
解法二:没有测试过,不知道是否正确
#include<bits/stdc++.h>
using namespace std;
const int N=10005;
int w[N],l[N],r[N],idx=1;
map<int,int> f;
map<int,int> st;
int ans;
int a[N];
void add(int u,int x)
{
int y=w[u];
if(x<y){
if(l[u]==0){
l[u]=idx;
w[idx]=x;
f[x]=y;
idx++;
return ;
}else add(l[u],x);
}else {
if(r[u]==0){
r[u]=idx;
w[idx]=x;
f[x]=y;
idx++;
return ;
}else add(r[u],x);
}
}
void find(int u)
{
if(st[u]==1){
ans=u;return;
}
st[u]=1;
if(f[u]!=-1)find(f[u]);
}
int main()
{
int m,n;cin>>m>>n;
for(int i=0;i<n;++i){
cin>>a[i];
int x=a[i];
if(idx==1){
w[idx++]=x;
}else add(1,x);
}
f[w[1]]=-1;
while(m--){
int x,y;cin>>x>>y;
if(f.find(x)==f.end()&&f.find(y)==f.end()){
printf("ERROR: %d and %d are not found.\n",x,y);
}else if(f.find(x)==f.end()){
printf("ERROR: %d is not found.\n",x);
}else if(f.find(y)==f.end()){
printf("ERROR: %d is not found.\n",y);
}else{
st.clear();
find(x);
find(y);
if(ans==x){
printf("%d is an ancestor of %d.\n",x,y);
}else if(ans==y){
printf("%d is an ancestor of %d.\n",y,x);
}else {
printf("LCA of %d and %d is %d.\n",x,y,ans);
}
}
}
return 0;
}