原题链接: UVA-536
题目大意:
输入一棵二叉树的先序遍历和中序遍历序列,输出后序遍历序列。
解题思路:
很基础的一道二叉树的题,和紫书中第六章中的一道例题很相似,边递归建树边输出。后序序列输出时应该将输出放在两个递归函数后面就可以后序序列。不难,不过还有些细节还是需要主要,比如传参的时候左右子树分别在先序和中序的位置需要注意。
代码:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
string preord, inord;
void crt_tree(int L1, int R1, int L2, int R2,int n)
{
if (L1 > R1 || L2 > R2) return;
char root = preord[L1]; int pos=0;
while (inord[pos] != root) pos++;
int len_left = pos - L2,len_right = R2 - pos;
crt_tree(L1 + 1, L1 + len_left, L2, pos - 1, 2 * n);
crt_tree(R1 - len_right+1, R1, pos + 1, R2, 2 * n + 1);
cout << root;
}
int main(){
while (cin >> preord>> inord){
int len = preord.length();
crt_tree(0, len - 1, 0, len - 1, 1);
cout << endl;
}
return 0;
}