没怎么写过树,欠的还是要还的。
目前看了题解是两种做法,一种是直接找,另一种是先建树再LCA(LCA用的裸查找)。
直接查找
a和b的最近公共祖先一定在中序遍历a的位置和中序遍历b的位置之间,而a和b的公共祖先一定在先序遍历中a和b的位置之前。在先序遍历中从0开始查找,找到的第一个中序遍历位置位于a和b之间的就是最近公共祖先。
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
int n, m;
int in[10005];
int pre[10005];
map<int, int> mp; //数据范围是int,要用map存
int main(){
scanf("%d%d", &m, &n);
for(int i = 0; i < n; i ++){
scanf("%d", &in[i]);
mp[in[i]] = i;
}
for(int i = 0; i < n; i ++) scanf("%d", &pre[i]);
for(int i = 0; i < m; i ++){
int a, b, flag1 = 1, flag2 = 1;
scanf("%d%d", &a, &b);
if(find(in, in+n, a)==in+n) flag1 = 0;
if(find(in, in+n, b)==in+n) flag2 = 0;
if(flag1 == 0 && flag2 == 0) printf("ERROR: %d and %d are not found.\n", a, b);
else if(flag1 == 0) printf("ERROR: %d is not found.\n", a);
else if(flag2 == 0) printf("ERROR: %d is not found.\n", b);
else{
int la = mp[a], lb = mp[b];
for(int j = 0; j < n; j ++){
int lj = mp[pre[j]];
if((la<lj&&lb>lj)||(la>lj&&lb<lj)){
printf("LCA of %d and %d is %d.\n", a, b, pre[j]);
break;
}
if(lj==la){
printf("%d is an ancestor of %d.\n", a, b);
break;
}
if(lj==lb){
printf("%d is an ancestor of %d.\n", b, a);
break;
}
}
}
}
return 0;
}
先建树,再LCA
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <map>
using namespace std;
int n, m;
int in[10005];
int pre[10005];
struct node{
int val;
node *l, *r, *parent;
};
map<int, node*> mp;
node* create(int preL, int preR, int inL, int inR){
if(preL>preR){
return NULL;
}
node* root = new node;
root->val = pre[preL];
int left = find(in+inL, in+inR+1, pre[preL])-in;
root->l = create(preL+1, preL+1+left-1-inL, inL, left-1);
root->r = create(preL+left+1-inL, preR, left+1, inR);
if(root->l != NULL) root->l->parent = root;
if(root->r != NULL) root->r->parent = root;
mp[root->val] = root;
return root;
}
int getL(node* p){
int l = 1;
while(p->parent != NULL){
p = p->parent;
l ++;
}
return l;
}
int lca(int a, int b){
node *node1 = mp[a], *node2 = mp[b];
int l1 = getL(node1), l2 = getL(node2);
while(l1 > l2){
node1 = node1->parent;
l1 --;
}
while(l2 > l1){
node2 = node2->parent;
l2 --;
}
while(node1 != node2){
node1 = node1->parent;
node2 = node2->parent;
}
return node1->val;
}
int main(){
scanf("%d%d", &m, &n);
for(int i = 0; i < n; i ++){
scanf("%d", &in[i]);
}
for(int i = 0; i < n; i ++) scanf("%d", &pre[i]);
node *root = create(0, n-1, 0, n-1);
for(int i = 0; i < m; i ++){
int a, b, flag1 = 1, flag2 = 1;
scanf("%d%d", &a, &b);
if(mp.count(a)==0) flag1 = 0;
if(mp.count(b)==0) flag2 = 0;
if(flag1 == 0 && flag2 == 0) printf("ERROR: %d and %d are not found.\n", a, b);
else if(flag1 == 0) printf("ERROR: %d is not found.\n", a);
else if(flag2 == 0) printf("ERROR: %d is not found.\n", b);
else{
int res = lca(a, b);
if(res==a) printf("%d is an ancestor of %d.\n", a, b);
else if(res==b) printf("%d is an ancestor of %d.\n", b, a);
else printf("LCA of %d and %d is %d.\n", a, b, res);
}
}
return 0;
}
注:left-inL
才是左子树的结点个数。