1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 struct Node{ 5 Node *lchild; 6 Node *rchild; 7 char c; 8 }; 9 Node *creat(){ 10 Node *T =(Node*)malloc(sizeof(Node)); 11 T->lchild=T->rchild=NULL; 12 return T; 13 } 14 char str1[30],str2[30]; 15 void post_order(Node *T){ 16 if(T->lchild!=NULL){ 17 post_order(T->lchild); 18 } 19 if(T->rchild!=NULL){ 20 post_order(T->rchild); 21 } 22 printf("%c",T->c); 23 } 24 Node *build(int s1,int e1,int s2,int e2){ 25 Node* ret=creat(); //为该树申请空间 26 ret->c=str1[s1]; 27 int rootIdx; 28 for(int i=s2;i<=e2;i++){ //查找该根节点在中序遍历中的顺序 29 if(str2[i]==str1[s1]){ 30 rootIdx=i; 31 break; 32 } 33 } 34 if(rootIdx!=s2){ //若左子树不为空 35 ret->lchild=build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1); 36 } //递归还原其左子树 37 if(rootIdx!=e2){ //若右子树不为空 38 ret->rchild=build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2); 39 } //递归还原其右子树 40 return ret;//返回根节点指针 41 42 43 44 } 45 46 int main(){ 47 scanf("%s",str1); 48 scanf("%s",str2); 49 int l1,l2; 50 l1=strlen(str1); 51 l2=strlen(str2); 52 Node *T=build(0,l1-1,0,l2-1); 53 post_order(T); 54 printf(" "); 55 56 57 return 0; 58 59 }