大意:有一个由最多26个大写字母构成的二叉树,如:
C
/ \
/ \
B G
/ \ /
A D H
/ \
E F
已知其前序遍历和中序遍历的结果,求其后序遍历。例如上面的树:
中序遍历串:ABEDFCHG
前序遍历串:CBADEFGH
计算得中序遍历串:AEFDBHGC
相当简单的一题:中序遍历串的第一个字母为根,在中序串中找到其位置,则左边的属于左子树,右边的属于右子树。递归调用并输出结果即可。
比较麻烦的是:如果串很长很长(当然,就不能用26字母表示了),不能使用递归时,如何用非递归实现?
/*
ID: blackco3
TASK: heritage
LANG: C++
*/
#include <iostream>
#include <memory.h>
using namespace std;
const int _max_(27) ;
char pre_str[_max_], in_str[_max_], post_str[_max_];
void recover( char *pre, char *in, char *post, int tsize )
{
post[tsize-1] = *pre ;
if( tsize==1 )
return ;
char *pin=in;
while( pin!=in+tsize && *pin!=*pre )
pin++;
if( (pin-in) )
recover( pre+1, in, post, pin-in );
if( tsize-(pin-in+1) )
recover( pre+(pin-in)+1, pin+1, post+(pin-in), tsize-(pin-in+1) );
}
int main() {
freopen("heritage.in", "r", stdin);
freopen("heritage.out", "w", stdout);
cin >> in_str >> pre_str ;
recover( pre_str, in_str, post_str, strlen(pre_str) );
post_str[strlen(pre_str)]='\0' ;
cout << post_str << endl ;
return 0 ;
}