题目链接如下:
看到一个很厉害的解法,UVA 536 - Tree Recovery ( 二叉树 )_little valentine liked playing with binary trees v-CSDN博客
我的代码如下:
#include <iostream>
#include <string>
// #define debug
std::string preord, inord;
int loc[26];
void post(int preL, int preR, int inL, int inR){
if (preL >= preR){
return;
}
int l = loc[preord[preL] - 'A'];
post(preL + 1, l - inL + preL + 1, inL, l);
post(l - inL + preL + 1, preR, l + 1, inR);
printf("%c", preord[preL]);
}
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
while (std::cin >> preord){
std::cin >> inord;
for (int i = 0; i < inord.size(); ++i){
loc[inord[i] - 'A'] = i;
}
post(0, preord.size(), 0, inord.size());
printf("\n");
}
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}