题意:
给出一棵二叉搜索树的前序遍历,问结点u和v的共同最低祖先是谁
思路:
这题我一开始的思路是建树,顺便建立前驱关系,然后就写,写完超时两个案例。正确思路是如果当前结点值在[u,v]之间,就说明该点为最低公共祖先,这个地方没想到,下面是别人的代码,非常简单,都不用建树。
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;
const int maxn = 15000;
int preorder[maxn];
map<int, bool> mapp;
int main() {
int k, n;
scanf("%d%d", &k, &n);
for (int i = 0; i < n; i++) {
scanf("%d", &preorder[i]);
mapp[preorder[i]] = true;
}
while (k--) {
int a, b,pos;
scanf("%d%d", &a, &b);
for (int i = 0; i < n; i++) {
pos = preorder[i];
if ((pos > a&&pos < b) || (pos<a&&pos>b) || (pos == a) || (pos == b))
break;
}
if (mapp[a] == false && mapp[b] == false) {
printf("ERROR: %d and %d are not found.\n", a, b);
} else if (mapp[a] == false || mapp[b] == false) {
printf("ERROR: %d is not found.\n", mapp[a] == false ? a : b);
} else if (pos == a || pos == b) {
printf("%d is an ancestor of %d.\n", pos, pos == a ? b : a);
} else {
printf("LCA of %d and %d is %d.\n", a, b, pos);
}
}
return 0;
}