1151 LCA in a Binary Tree (30 分) (前序中序遍历 0/30
作者:互联网
添加链接描述
通过map记录下标 进行遍历,可以直接得到pre的根
这样就不需要k++,在建树的过程中寻找如果下标都在根两边说明找到了最近的点,否则就往两边找
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+9;
int in[N],pre[N];
int n,q;
int ok=0;
unordered_map<int,int>pt;
void lca(int inl,int inr,int root,int a,int b){
if(ok)return;
if(inr<inl)return ;
int k=pt[pre[root]];
int pta=pt[a],ptb=pt[b];
if(pta<k&&ptb<k){
lca(inl,k-1,root+1,a,b);
}
else if(pta>k&&ptb>k){
lca(k+1,inr,root+(k-inl)+1,a,b);
}
else if((pta<k&&ptb>k)||(pta>k&&ptb<k)){
printf("LCA of %d and %d is %d.\n",a,b,pre[root]);//!!pre[root]
ok=1;
return;
}
else if(pta==k){
printf("%d is an ancestor of %d.\n",a,b);
ok=1;
return;
}
else {
printf("%d is an ancestor of %d.\n",b,a);
ok=1;
return ;
}
}
int main(){
cin>>q>>n;
for(int i=1;i<=n;i++){
scanf("%d",&in[i]);
pt[in[i]]=i;
}
for(int i=1;i<=n;i++){
scanf("%d",&pre[i]);
}
while(q--){
int a,b;
scanf("%d%d",&a,&b);
if(pt[a]==0&&pt[b]==0){
printf("ERROR: %d and %d are not found.\n",a,b);
}
else if(pt[a]==0||pt[b]==0){
printf("ERROR: %d is not found.\n",pt[a]==0?a:b);
}
else {
ok=0;
lca(1,n,1,a,b);
}
}
return 0;
}
标签:pre,Binary,ok,pt,int,前序,30,else,printf 来源: https://blog.csdn.net/Minelois/article/details/123136816