前序+中序->后序
#include <bits/stdc++.h>
using namespace std;
struct node
{
char elem;
node* l;
node* r;
};
node* dfs(char* pre,char* in,int len) //前序首地址、中序首地址、整个数组对应的长度
{
int i;
if(len==0)
return NULL;
node* =new node;
s->elem=*(pre);
for(i=0; i<len; i++)
if(in[i]==*(pre))
break;
//cout<<s->elem; 前序
s->l=dfs(pre+1,in,i);
//cout<<s->elem; 中序
s->r=dfs(pre+1+i,in+i+1,len-1-i);
cout<<s->elem; //后序
return s;
}
int main()
{
char s1[31],s2[31];
while(~scanf("%s",s1))
{
cin>>s2;
int len=strlen(s1);
node* s=dfs(s1,s2,len);
cout<<endl;
}
return 0;
}
中序+后序->前序
#include <bits/stdc++.h>
using namespace std;
struct node
{
char elem;
node* l;
node* r;
};
node* dfs(char* in,char* post,int len)
{
if(len == 0) return NULL;
node *s = (node *)malloc(sizeof(node));
s->elem = *(post+len-1);
int i;
for(i=len-1; i>=0; i--)
{
if(in[i] == s->elem)
break;
}
printf("%c", s->elem);
s->l = dfs(in, post, i);
s->r = dfs(in+i+1, post+i, len-1-i);
return s;
}
int main()
{
char s1[31],s2[31];
while(~scanf("%s",s1))
{
cin>>s2;
int len=strlen(s1);
node* s=dfs(s1,s2,len);
cout<<endl;
}
return 0;
}