题目链接:http://acm.tju.edu.cn/toj/showp.php?pid=1144
题目大意:给出二叉树的先序遍历和后续遍历 求中序遍历
思路:上递归模板
//给出先序遍历和中序遍历,求后序遍历
#include<iostream>
#include<cstring>
using namespace std;
string preorder, inorder;
void solve(int pst,int pend,int ist,int iend)
{
int i;
if(pst>pend||ist>iend)
return;
for(i=0;i<=iend;i++)
if(preorder[pst]==inorder[i]) //在中序中找到根 然后左右分
break;
solve(pst+1,pst+i-ist,ist,i-1); //左子树
solve(pst+i-ist+1,pend,i+1,iend); //右子树
cout<<preorder[pst]; //后续遍历 最后输出根
return;
}
int main()
{
while(cin>>preorder>>inorder)
{
solve(0,preorder.length()-1,0,inorder.length()-1); //起始元素,结束元素
cout<<endl;
}
}