跟LEETCODE的preorder,inorder转postorder题很像
#include <iostream> #include <stdio.h> #include <string> #include <stack> #include <map> #include <vector> #include <algorithm> using namespace std; struct node { char val; node *left, *right; node(char v) : val(v), left(NULL), right(NULL) { } }; node* preIn(string preorder, string inorder, int prebeg, int inbeg, int len) { if (!len) return NULL; node *tmp = new node(preorder[prebeg]); int leftlen, rightlen; for (int i = inbeg; i < inbeg+len; ++i) { if (tmp->val == inorder[i]) { leftlen = i - inbeg; rightlen = len - leftlen - ; break; } } tmp->left = preIn(preorder, inorder, prebeg+, inbeg, leftlen); tmp->right = preIn(preorder, inorder, prebeg+leftlen+, inbeg+leftlen+, rightlen); return tmp; } string postString(node *root) { if (!root) return ""; return postString(root->left) + postString(root->right) + root->val; } int main() { string preorder, inorder; while (cin >> preorder && cin >> inorder) { node *root = preIn(preorder, inorder, , , preorder.size()); string postorder = postString(root); cout << postorder << endl; } ; }