也是根据两个已知的遍历顺序推导出另外一个遍历,我采用的是还原该树的方法,然后用递归遍历。
附本人代码:
#include<iostream>
#include<vector>
#include<stack>
#include<string>
#include<map>
using namespace std;
bool flag = false;
struct Node {
int lchild, rchild;
};
map<int, Node>Ma;
vector<int>Vpre, Vin;
int findroot(int begin, int end, int index) {
if (begin > end)return -1;
int root;
for (int i = begin; i <= end; i++) {
if (Vin[i] == Vpre[index]) {
root = i;
break;
}
}
int rchild = index + root - begin + 1;
int lchild = index + 1;
if (root - begin >= 1)Ma[Vpre[index]].lchild = findroot(begin, root - 1, lchild);
if (end - begin >= 1)Ma[Vpre[index]].rchild = findroot(root + 1, end, rchild);
return Vin[root];
}
void post(int val) {
if(Ma[val].lchild>0)post(Ma[val].lchild);
if(Ma[val].rchild>0)post(Ma[val].rchild);
if (val > 0) {
if (!flag) {
printf("%d", val);
flag = true;
}
else printf(" %d", val);
}
}
int main() {
int N, val;
stack<int>Q;
string s;
cin >> N;
for (int i = 0; i < 2 * N; i++) {
cin >> s;
if (s == "Push") {
cin >> val;
Vpre.push_back(val);
Q.push(val);
}
else {
Vin.push_back(Q.top());
Q.pop();
}
}
findroot(0, N - 1, 0);
post(Vpre[0]);
return 0;
}