1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include<iostream> #include<string> using namespace std;
void postorder(string preorder, string inorder) { int len = preorder.length(); if (len == 0) return; if (len == 1) { cout << preorder[0]; return; } int pos = inorder.find(preorder[0]); postorder(preorder.substr(1, pos), inorder.substr(0, pos)); postorder(preorder.substr(pos + 1, len - pos - 1), inorder.substr(pos + 1, len - pos - 1)); cout << preorder[0]; } void preorder(string inorder, string postorder) { int len = postorder.length(); if (len == 0) return; if (len == 1) { cout << inorder[0]; return; } int pos = inorder.find(postorder[len - 1]); cout << postorder[len - 1]; preorder(inorder.substr(0, pos), postorder.substr(0, pos)); preorder(inorder.substr(pos + 1, len - pos - 1), postorder.substr(pos, len - pos - 1)); } int main() { string s1, s2; while (cin >> s1 >> s2) { postorder(s1, s2); cout << endl; } }
|