UVa 536 Tree Recovery

题目:

  一直树的前序遍历和中序遍历,求后序遍历。

分析:

  递归.对于每个子树,前根序第一个是根,找到它在中根序的位置,就能确定左右子树,然后递归求解。

代码:

  

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
char tq[27],tz[27],th[27];
void build(int p1,int p2,int q1,int q2,int d)
{
if(p1>p2)
return;
for(d=q1;tq[p1]!=tz[d];++d);
build(p1+1,p1-q1+d,q1,d-1,0);
build(p1+1+d-q1,p2,d+1,q2,0);
cout<<tz[d];
}
int main()
{
while(cin>>tq>>tz)
{
int l=strlen(tq)-1;
build(0,l,0,l,0);
cout<<endl;
}
}
posted @ 2015-10-14 10:11  幻世沉溺  阅读(220)  评论(0编辑  收藏  举报