题意:已知先序中序,输出后序。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 26 + 10; const int MAXT = 10000 + 10; using namespace std; char pre_order[MAXN]; char in_order[MAXN]; int leftchild[MAXN]; int rightchild[MAXN]; int build(int L1, int R1, int L2, int R2){ if(L1 > R1) return 0; int root = pre_order[L1] - ‘A‘ + 1; int st = L2; while((in_order[st] - ‘A‘ + 1) != root) ++st; int cnt = st - L2; leftchild[root] = build(L1 + 1, L1 + cnt, L2, L2 + cnt - 1); rightchild[root] = build(L1 + 1 + cnt, R1, st + 1, R2); return root; } void dfs(int root){ if(leftchild[root]) dfs(leftchild[root]); if(rightchild[root]) dfs(rightchild[root]); printf("%c", root + ‘A‘ - 1); } int main(){ while(scanf("%s", pre_order) != EOF){ scanf("%s", in_order); int len = strlen(pre_order); build(0, len - 1, 0, len - 1); int root = pre_order[0] - ‘A‘ + 1; dfs(root); printf("\n"); } return 0; }
UVA - 536 Tree Recovery (二叉树重建)
原文:http://www.cnblogs.com/tyty-Somnuspoppy/p/6279848.html