#include <iostream>
using namespace std;
void BinaryTreeFromOrderHelper(string InOrder,string PreOrder,int length, string&res)
{
if(length == 0)
{
return;
}
char val = PreOrder[0];
int rootIndex = 0;
for(;rootIndex < length; rootIndex++)
{
if(InOrder[rootIndex] == val)
break;
}
BinaryTreeFromOrderHelper(InOrder,PreOrder.substr(1), rootIndex, res);
BinaryTreeFromOrderHelper(InOrder.substr(rootIndex+1), PreOrder.substr(rootIndex+1), length-(rootIndex+1),res);
res+=val;
}
string PostOrder(string InOrder, string PreOrder)
{
string res;
BinaryTreeFromOrderHelper(InOrder, PreOrder, InOrder.length(), res);
return res;
}
int main() {
cout<<PostOrder("ADEFGHMZ","GDAFEMHZ "); //AEFDHZMG
return 0;
}
思路:
1,figure out the root, then find the left subtree and right subtree
2,recurse in the left subtree
3,recurse int he right subtree
4,print out the root
//中序遍历和后序遍历求前序遍历
//已知前序和后序能确定中序吗?