题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG BCAD CBAD
样例输出
ACBFGED CDAB
#include<stdio.h>
#include<string.h>
struct node{char data;node* lChild;node* rChild;
};
char pre[100],in[100];
node* create(int preL,int preR,int inL,int inR){if(preL>preR)return NULL;node* root=new node;root->data=pre[preL];int i;for(i=inL;i<=inR;i++){if(in[i]==pre[preL])break;}int numLeft=i-inL;root->lChild=create(preL+1,preL+numLeft,inL,i-1);root->rChild=create(preL+numLeft+1,preR,i+1,inR);return root;
}
void postorder(node* root)
{if(root==NULL){return;}postorder(root->lChild);postorder(root->rChild);printf("%c",root->data);
}
int main()
{while(scanf("%s %s",pre,in)!=EOF){//printf("%s %s\n",pre,mid);int preLen=strlen(pre);int inLen=strlen(in);postorder(create(0,preLen-1,0,inLen-1));printf("\n");}return 0;
}