Description
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F
Input
Output
Sample Input
DBACEGF ABCDEFG BCAD CBAD
Sample Output
ACBFGED CDAB
法一:非递归
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 using namespace std; 5 6 string s1,s2; 7 8 typedef struct node{ 9 int pt; 10 char x; 11 struct node *left; 12 struct node *right; 13 }node; 14 15 void postorder(node *root){ 16 if(root==NULL) return; 17 postorder(root->left); 18 postorder(root->right); 19 cout<<root->x; 20 } 21 22 int main() 23 { 24 int i,j; 25 26 while(cin>>s1>>s2){ 27 node *root=new(node); 28 root->left=NULL; 29 root->right=NULL; 30 root->x=s1[0]; 31 root->pt=0; 32 for(j=0;j<(int)s2.length();j++){ 33 if(s1[0]==s2[j]) 34 break; 35 } 36 root->pt=j; 37 38 for(i=1;i<(int)s1.length();i++){ 39 for(j=0;j<(int)s2.length();j++){ 40 if(s1[i]==s2[j]) 41 break; 42 } 43 node *p=root, *pre=NULL; 44 45 while(p){ 46 pre=p; 47 48 if(j<p->pt){ 49 p=p->left; 50 }else{ 51 p=p->right; 52 } 53 54 } 55 node *t=new(node); 56 t->left=NULL; 57 t->right=NULL; 58 t->x=s1[i]; 59 t->pt=j; 60 if(j<pre->pt){ 61 pre->left=t; 62 }else{ 63 pre->right=t; 64 } 65 } 66 postorder(root); 67 cout<<endl; 68 } 69 return 0; 70 }
法二:递归
1 #include<stdio.h> 2 #include<string.h> 3 void build(int n,char*s1,char*s2) 4 { 5 if(n<=0)return ; 6 int p=strchr(s2,s1[0])-s2; 7 build(p,s1+1,s2); 8 build(n-p-1,s1+p+1,s2+p+1); 9 printf("%c",s1[0]); 10 } 11 int main() 12 { 13 char s1[30],s2[30],ans[30]; 14 memset(s1,0,sizeof(s1)); 15 memset(s2,0,sizeof(s2)); 16 while(scanf("%s %s",s1,s2)!=EOF) 17 { 18 int n=strlen(s1); 19 build(n,s1,s2); 20 ans[n]='\0'; 21 printf("\n"); 22 } 23 return 0; 24 }