1151. LCA in a Binary Tree

二叉树上寻找最近公共祖先

需要注意节点的key不一定连续

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;

struct node {
int left, right, parent, depth;
};

unordered_map<int, node> N;

int build(const vector<int>::iterator &preord_b,
const vector<int>::iterator &preord_e,
const vector<int>::iterator &inord_b,
const vector<int>::iterator &inord_e,
int parent,
int depth)
{
if (preord_b == preord_e)
return 0;
int key = *preord_b;
auto inord_mid = find(inord_b, inord_e, key);
int left_len = inord_mid - inord_b;
N[key].left = build(preord_b + 1, preord_b + 1 + left_len, inord_b,
inord_mid, key, depth + 1);
N[key].right = build(preord_b + 1 + left_len, preord_e, inord_mid + 1,
inord_e, key, depth + 1);
N[key].parent = parent;
N[key].depth = depth;
return key;
}

int lca(int a, int b)
{
if (a == b) {
return a;
} else if (N[a].depth > N[b].depth) {
return lca(N[a].parent, b);
} else if (N[a].depth < N[b].depth) {
return lca(N[b].parent, a);
}
return lca(N[a].parent, N[b].parent);
}

int main()
{
int m;
cin >> m;
int n;
cin >> n;

vector<int> inord(n), preord(n);
for (int i = 0; i < n; i++)
cin >> inord[i];
for (int i = 0; i < n; i++)
cin >> preord[i];

int root =
build(preord.begin(), preord.end(), inord.begin(), inord.end(), 0, 0);

for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
bool e1 = (N.find(u) == N.end());
bool e2 = (N.find(v) == N.end());

if (e1 && e2) {
cout << "ERROR: " << u << " and " << v << " are not found." << endl;
continue;
} else if (e1 || e2) {
cout << "ERROR: " << (e1 ? u : v) << " is not found." << endl;
continue;
}

int a = lca(u, v);
if (a == u || a == v) {
cout << a << " is an ancestor of " << (a == u ? v : u) << "."
<< endl;
} else {
cout << "LCA of " << u << " and " << v << " is " << a << "."
<< endl;
}
}

return 0;
}