题目:http://www.nocow.cn/index.php/Translate:USACO/heritage 很简单,知道前序,中序排列,求二叉树的后序排列。递归一下轻松搞定。 #include <iostream> #include <fstream> #include<string.h> #define SIZE 27 using namespace std; char pre[SIZE]; char middle[SIZE]; char last[SIZE]; int l = 0; int lastindex = 0; void getLast(int head, int start, int end) { for (int i = start; i < end; i ++) { if (middle[i] == pre[head]) { getLast(head + 1, start, i); getLast(head + i - start +1, i+1, end); last[lastindex] = pre[head]; lastindex ++; break; } } } int main() { ifstream fin("heritage.in"); ofstream fout("heritage.out"); char str[30]; fin >> str; l = strlen(str); for (int i=0; i < l; i ++) { middle[i] = str[i]; } fin >> str; for(int i=0; i <l; i ++) { pre[i] = str[i]; } getLast(0,0,l); last[l] = '/0'; fout<<last <<endl; return 0; } 运行结果: Executing... Test 1: TEST OK [0.011 secs, 3016 KB] Test 2: TEST OK [0.011 secs, 3016 KB] Test 3: TEST OK [0.000 secs, 3016 KB] Test 4: TEST OK [0.011 secs, 3016 KB] Test 5: TEST OK [0.011 secs, 3016 KB] Test 6: TEST OK [0.011 secs, 3016 KB] Test 7: TEST OK [0.011 secs, 3016 KB] Test 8: TEST OK [0.011 secs, 3016 KB] Test 9: TEST OK [0.000 secs, 3016 KB] All tests OK.