已知前序和中序遍历,求后序遍历
一直以为这种题是先建树,然后在调整之类的,看了上面的提示,发现可以分而治之的思想,前序遍历是根左右,中序遍历是左根右,两者结合就可以找到左子树和右子树,这样一直找到叶子阶段,然后递归就是左子树+右子树+根得到后续遍历。
看了http://www.cnblogs.com/pinxiong/p/4077900.html写的很好,我就做了c++版本的,学习了!
#include <iostream>
#include <algorithm>
#include <string>
#define MAX 1000000010
using namespace std;
int findchar(string str,char ch)
{
for(int i=0;i<str.length();i++)
{
if(ch==str[i])
return i;
}
return -1;
}
string post_order(string pre,string mid)//输入前序遍历和中序遍历,输出后序遍历
{
if(pre.length()>0)
{
char root;
root=pre[0];//每次找到根
int pos=findchar(mid,root);
if(pos!=-1)
{
string left=mid.substr(0,pos);//中序遍历的左子树
string right=mid.substr(pos+1);//右子树
return post_order(pre.substr(1,left.length()),left)+
post_order(pre.substr(left.length()+1),right)+root;
}
}
return "";
}
int main()
{
string str1,str2;
cin>>str1>>str2;
cout<<post_order(str1,str2)<<endl;
}