先序后序求中序
代码如下:
# include<cstdio>
# include<string.h>
using namespace std;
void w(int n,char *s1,char *s2,char *s)
{
if(n<=0) return ;
int p=strchr(s2,s1[0])-s2;
w(p,s1+1,s2,s);
w(n-1-p,s1+p+1,s2+p+1,s+p);
s[n-1]=s1[0];
}
int main(){
char s1[40],s2[40],s[40]; //s1 先序序列,s2 中序序列
while(~scanf("%s%s",s1,s2))
{
int n=strlen(s1);
s[n]=0;
w(n,s1,s2,s);
printf("%s\n",s);
}
return 0;
}
中序后序求先序
代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
string mid;
string last;
void dfs(int l,int r,int z,int y)
{
if(l>r||z>y) return ;
cout<<last[y];
for(int i=l;i<=r;i++)
{
if(last[y]==mid[i])
{
dfs(l,i-1,z,z+i-l-1);
dfs(i+1,r,z+i-l,y-1);
}
}
}
int main()
{
cin>>mid; //中序序列
cin>>last; //后序序列
int l=strlen(&mid[0]);
dfs(0,l-1,0,l-1);
}