题意:给出树的先序和中序,按后序输出。
思路:
递归建树:
将结点的值直接用作建树的下标,因为是字母,所以要转化成数字,A-1 B-2...Z-26
(1)将先序和中序的头和尾位置进行递归,
(2)每次寻找到根结点,然后通过根结点计算出先序和中序的左树和右树的位置,再进行递归;
(3)每次递归返回的值存放到左树数组和右树数组即建树
(4)以上已经将左树和右树的位置存放到对应的数组中,按后序递归数组位置输出值即可。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int lch[30],rch[30];
char s1[30],s2[30];
int build(int l1,int r1,int l2,int r2){//递归建树,分别将先序的头和尾,和中序的头和尾进行递归
if(l2 > r2) return 0;//空树
int root = s1[l1] - 'A' + 1;//先序的第一个位置即为根,直接保存根值(将字母转化为数字)
int p = l2;
while(s2[p] - 'A' + 1 != root) p++;//将中序的根位置找到。
int cnt = p - l2;//计算左树的结点个数
lch[root] = build(l1+1,l1+1+cnt-1,l2,p-1);//分别将先序和中序的左树位置传入递归,且返回存入保存左子树结点的数组中
rch[root] = build(l1+1+cnt-1+1,r1,p+1,r2);//同理将右树传入递归,且同理返回数组中
return root;//每次返回根结点
}
void dfs(int u){//按后序递归输出
if(lch[u]) dfs(lch[u]);
if(rch[u]) dfs(rch[u]);
printf("%c",u+'A'-1);
return;}
int main()
{
while(scanf("%s",s1)!=EOF){
scanf("%s",s2);
int len = strlen(s1);
build(0,len-1,0,len-1);
dfs(s1[0]-'A'+1);
printf("\n");
}
return 0;}