先建立一个BST树后再找LCA会导致最后三个测试点超时
可以直接遍历先序序列:
由于先序序列永远先访问子树根节点,所以第一个找到的u<root<v或u>root>v一定是u和v的LCA;若先找到u或先找到v,则先找到的那个一定是另一个的祖先。
#include <iostream>
#include <unordered_set>
#include <algorithm>
using namespace std;
unordered_set<int> nodes;
int preOrder[10010];
int main(){
int m,n;
scanf("%d%d",&m,&n);
for(int i = 0;i < n;i++){
scanf("%d",&preOrder[i]);
nodes.insert(preOrder[i]);
}
for(int i = 0;i < m;i++){
int u,v;
scanf("%d%d",&u,&v);
bool uInTree = nodes.find(u) != nodes.end();
bool vInTree = nodes.find(v) != nodes.end();
if(uInTree == false && vInTree == false){
printf("ERROR: %d and %d are not found.\n",u,v);
continue;
}
else if(uInTree == false){
printf("ERROR: %d is not found.\n",u);
continue;
}else if(vInTree == false){
printf("ERROR: %d is not found.\n",v);
continue;
}
for(int j = 0;j < n;j++){
if(preOrder[j] == u){
printf("%d is an ancestor of %d.\n",u,v);
break;
}
else if(preOrder[j] == v){
printf("%d is an ancestor of %d.\n",v,u);
break;
}
else if((u < preOrder[j] && v > preOrder[j]) || (u > preOrder[j] && v < preOrder[j])){
printf("LCA of %d and %d is %d.\n",u,v,preOrder[j]);
break;
}
}
}
system("pause");
return 0;
}