题目
思路
和1143差不多,主要是查找函数有变化,这个是要每次将整颗树遍历一遍,而1141是遍历到结点就行了。
代码
测试点1有误,望大神解答
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool found1 = false, found2 = false;
vector<int> pre, in;
typedef struct node {
int val;
node* lchild, * rchild;
}*tree;
void init(tree& t, int low, int high, int cur) {
if (low > high)
return;
t = new node();
t->val = pre[cur];
t->lchild = t->rchild = nullptr;
int _index = low;
while (_index <= high && in[_index] != pre[cur]) ++_index;
int bias = _index - low;
init(t->lchild, low, _index - 1, cur + 1);
init(t->rchild, _index + 1, high, cur + bias + 1);
}
void find1(vector<int>& vec, tree& t, int val) {
if (t->val == val) {
found1 = true;
return;
}
if (t->lchild != nullptr) {
if (!found1)
vec.emplace_back(t->lchild->val);
find1(vec, t->lchild, val);
if (!found1)
vec.pop_back();
}
if (t->rchild != nullptr) {
if (!found1)
vec.emplace_back(t->rchild->val);
find1(vec, t->rchild, val);
if (!found1)
vec.pop_back();
}
}
void find2(vector<int>& vec, tree& t, int val) {
if (t->val == val) {
found2 = true;
return;
}
if (t->lchild != nullptr) {
if (!found2)
vec.emplace_back(t->lchild->val);
find2(vec, t->lchild, val);
if (!found2)
vec.pop_back();
}
if (t->rchild != nullptr) {
if (!found2)
vec.emplace_back(t->rchild->val);
find2(vec, t->rchild, val);
if (!found2)
vec.pop_back();
}
}
int main()
{
int n, qn;
cin >> qn >> n;
pre.resize(n);
in.resize(n);
for (int i = 0; i < n; ++i) cin >> in[i];
for (int i = 0; i < n; ++i) cin >> pre[i];
tree t;
init(t, 0, n - 1, 0);
for (int i = 0; i < qn; ++i) {
int u, v;
cin >> u >> v;
vector<int> vec1, vec2;
find1(vec1, t, u);
find2(vec2, t, v);
if (!found1 && !found2) {
cout << "ERROR: " << u << " and " << v << " are not found." << endl;
found1 = found2 = false;
continue;
}
else if (!found1 && found2) {
cout << "ERROR: " << u << " is not found." << endl;
found1 = found2 = false;
continue;
}
else if (found1 && !found2) {
cout << "ERROR: " << v << " is not found." << endl;
found1 = found2 = false;
continue;
}
bool flag = false;
int tar, j;
for (j = 0; j < vec1.size() && j < vec2.size(); ++j) {
if (vec1[j] != vec2[j]) {
flag = true;
tar = vec1[j - 1];
break;
}