问题:http://hihocoder.com/problemset/problem/1049?sid=767510
已知一棵二叉树的前序遍历及中序遍历结果,求后序遍历结果
思路:
前序:根-左子树-右子树
中序:左子树-根-右子树
后序:左子树-右子树-根
递归的方法,从前序得到根结点,然后根据中序发现两个子树。先求子树的后序遍历结果,再把当前的根添加在最后即可。
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 void toPostOrder(string preOrder, string inOrder, string& postOrder, int len){ 6 if (len <= 0) 7 return; 8 int i = 0; 9 for (; i < len; i++) 10 if (preOrder[0] == inOrder[i]) 11 break; 12 13 toPostOrder(preOrder.substr(1), inOrder, postOrder, i); 14 toPostOrder(preOrder.substr(i + 1), inOrder.substr(i + 1), postOrder, len - i - 1); 15 postOrder.push_back(preOrder[0]); 16 } 17 18 int main(){ 19 string preOrder, inOrder; 20 cin >> preOrder >> inOrder; 21 string postOrder; 22 toPostOrder(preOrder, inOrder, postOrder, preOrder.length()); 23 cout<<postOrder<<endl; 24 return 0; 25 }