思路:
1.将两个遍历结果分别存入两个字符数组中
struct Node{
Node* lchild;
Node* rchild;
char c;
}tree[50];
int size = 0;
char a[50],b[50];
Node* create()
{
tree[size].lchild=tree[size].rchild=NULL;
return &tree[size++];
}
2.后序遍历的实现
void postorder(Node *r)
{
if (r==NULL) {
return ;
}
postorder(r->lchild);
postorder(r->rchild);
cout<<r->c;
}
3.递归的方式还原树
Node* build(int b1,int e1,int b2,int e2)
{
Node *ret = create();
ret->c=a[b1];
int index;
for (int i=b2; i<=e2; i++) {
if (a[b1]==b[i]) {
index=i;
break;
}
}
if (index!=b2) { //左子树非空
ret->lchild=build(b1+1, b1+index-b2, b2, index-1);
}
if (index!=e2) { //右子树非空
ret->rchild=build(b1+index-b2+1, e1, index+1, e2);
}
return ret;
}
4.主函数形式
int main()
{
while (cin>>a) {
cin>>b;
Node *root = build(0,strlen(a)-1,0,strlen(b)-1);
postorder(root);
cout<<endl;
}
return 0;
}