UVa 536 Tree Recovery | GOJ 1077 Post-order (习题 6-3)
传送门1: https://uva.onlinejudge.org/external/5/536.pdf
传送门2: http://acm.gdufe.edu.cn/Problem/read/id/1077
题意一样 输入不一样
HINT:
1. Preorder : (root, left subtree, right subtree);
Inorder : (left subtree, root, right subtree);
Postorder: (left subtree, right subtree, root);
2. 对于preorder,第一个元素即为整棵树的根
且在preorder中,待求子树结点靠前为根结点
3. 以找到的点为界,将inorder划分为两棵子树
#include <bits/stdc++.h> using namespace std; string pre, in; int length; char ans[30]; void process(int l, int r){ if(l > r) return; bool flag = false; char ch; int mid; for(int i = 0; i < pre.length(); ++i){ for(int j = l; j <= r; ++j){ if(pre[i] == in[j]){ flag = true; ch = pre[i]; mid = j; break; } } if(flag) break; } ans[--length] = ch;
//注意先右后左(后序遍历从左到右再到根) process(mid + 1, r); process(l, mid - 1); } int main(){ while(cin >> pre >> in){ length = pre.length(); process(0, length - 1); for(int i = 0; i < pre.length(); ++i) cout << ans[i]; cout << endl; } return 0; }
另一种做法是建树模拟,贴上小光师兄博客里这道题的链接: http://blog.csdn.net/u012469987/article/details/41294313