/**
已知中序遍历和后序遍历,求前序遍历
算法的主要部分是将中序遍历分成左中右三部分
将后序遍历分成左右中三部分
最后后序建树的时候节点就等于中间的部分
左子树由中序遍历的左部分和后序遍历的左部分构建
右子树由中序遍历的右部分和后序遍历的右部分构建
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <malloc.h>
using namespace std;
struct node
{
int val;
node *left, *right;
};
node* create(char *zhong, char *hou, int len)//后序建树
{
if (len<=0)
return NULL;
node *head = (node*)malloc(sizeof(node));
head->val = *(hou+len-1);
char *ph = hou+len-1;//后序遍历的根
char *pt;
for (pt=zhong; pt!=NULL; pt++)
if (*pt==*ph)//找中序遍历中与后序遍历的根相同的点
break;
int k = pt-zhong;
head->left = create(zhong, hou, k);//创建左子树
head->right = create(pt+1, hou+k, len-k-1);//创建右子树
return head;
}
void print(node *head)
{
if (head==NULL)
return ;
printf("%c", head->val);
print(head->left);
print(head->right);
}
int main()
{
char zhong[100], hou[100];
while (~scanf("%s%s", zhong, hou))
{
int len = strlen(zhong);
node* head = create(zhong, hou, len);
print(head);
printf("\n");
}
return 0;
}