第一个完全由自己想出来的递归程序,嘿嘿。
#include <iostream> #include <string> using namespace std; /*核心函数。递归实现。 *preStr为先序遍历串,inStr为中序遍历串。 *假设preStr为“BCAD”,inStr为“CBAD”。 *则先找到根为”B“,根的左孩子为”C“,右孩子为”AD“。 *然后递归调用postStr,得到左孩子和右孩子的后序遍历串,再加上根即可。 */ string postStr(string preStr, string inStr) { if(preStr.size() == 0) return ""; else if(preStr.size() == 1) return preStr; else { string::size_type rootPosInInStr = inStr.find(preStr[0]); string::size_type leftChildSize = rootPosInInStr; string::size_type rightChildSize = inStr.size() - leftChildSize - 1; /*注意,若string::substr()查找不到相应子串,则返回空串(size == 0, 而不是返回NULL)*/ return postStr(preStr.substr(1, leftChildSize), inStr.substr(0, leftChildSize)) + postStr(preStr.substr(preStr.size() - rightChildSize), inStr.substr(rootPosInInStr + 1)) + preStr[0]; } } int main() { string preStr, inStr; while(cin >> preStr >> inStr) { cout << postStr(preStr, inStr) << endl; } return 0; }