刘汝佳小白书上有递归写法的源代码。
/*
ID:jinbo wu
LANG:C++
TASK:heritage
*/
#include<bits/stdc++.h>
using namespace std;
void solve(int n,char *s1,char *s2,char *s)
{
if(n<=0) return ;
int p=strchr(s2,s1[0])-s2;
solve(p,s1+1,s2,s);
solve(n-p-1,s1+p+1,s2+p+1,s+p);
s[n-1]=s1[0];
}
int main()
{
freopen("heritage.in","r",stdin);
freopen("heritage.out","w",stdout);
char s1[30];
char s2[30];
char ans[30];
cin>>s1;
cin>>s2;
int n=strlen(s1);
solve(n,s2,s1,ans);
ans[n]='\0';
cout<<ans<<endl;
}
过几天数据结构考试没准要考这个顺便把后序,中序求先序也写出来。
#include<bits/stdc++.h>
using namespace std;
void build(int n,char *s1,char*s2,char*s)
{
if(n<=0) return;
int p=strchr(s2,s1[n-1])-s2;
s[0]=s1[n-1];
build(p,s1,s2,s+1);
build(n-p-1,s1+p,s2+p+1,s+p+1);
}
int main()
{
char s1[30],s2[30],ans[30];
cin>>s1>>s2;
build(strlen(s1),s1,s2,ans);
ans[strlen(s1)]='\0';
cout<<ans<<endl;
}