题目大意:
给你中序和先序遍历的序列,要你输出后序遍历的结果。
思路:根据中序和先序建树然后后序输出即可。
代码:
#include<iostream>
#include<string.h>
#include<cstring>
using namespace std;
const int maxn = 10000;
char pre[maxn];
char in[maxn];
char l[maxn];
char r[maxn];
char build(int l1, int r1, int l2, int r2) {
if (l1 > r1 || l2 > r2)return 0;
char root = pre[l1];
int k;
for (int i = 0; i < strlen(in); i++) {
if (root == in[i]) {
k = i;
break;
}
}
int p = k - l2;
l[root - 'A'] = build(l1 + 1, l1 + p, l2, p - 1+ l2);
r[root - 'A'] = build(l1 +p + 1, r1, p + 1+ l2, r2);
return root;
}
void postorder(char root) {
if (root == '\0')return;
postorder(l[root - 'A']);
postorder(r[root - 'A']);
cout << root;
}
int main() {
while (cin >> pre >> in) {
int n = strlen(pre) - 1;
build(0, n, 0, n);
postorder(pre[0]);
cout<<endl;
}
}