不断地在前序中找到树与子树的根节点,在中序中对应,并存入树型结构。
1.建树:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
typedef struct node{
char d;
node*l,*r;
}*Tree;
Tree root;
char pre[100],mid[100];
void maketree(Tree &t,int pl,int pr,int ml,int mr){
t=new node;
t->d=pre[pl];
t->l=t->r=NULL;
int i=ml;
while(mid[i]!=pre[pl])i++;
int len=i-ml;
if(i>ml)
maketree(t->l,pl+1,pl+len,ml,i-1);
if(i<mr)
maketree(t->r,pl+len+1,pr,i+1,mr);
}
void out(Tree t){
if(t){
out(t->l);
out(t->r);
printf("%c",t->d);
}
}
int main(){
gets(pre);
gets(mid);
maketree(root,0,strlen(mid)-1,0,strlen(mid)-1);
out(root);
return 0;
}
2.不建树
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
char d;
node*l,*r;
}*Tree;
Tree root;
char pre[100],mid[100];
void out(char ps[],char ms[]){
int i,len;
char s1[100],s2[100];
len=strlen(ps);
i=strchr(ms,ps[0])-ms;
if(i>0){
memcpy(s1,&ps[1],i);s1[i]=0;
memcpy(s2,&ms[0],i);s2[i]=0;
out(s1,s2);
}
if(i<len-1){
memcpy(s1,&ps[i+1],len-1-i);s1[len-1-i]=0;
memcpy(s2,&ms[i+1],len-1-i);s2[len-1-i]=0;
out(s1,s2);
}
printf("%c",ps[0]);
}
int main(){
gets(pre);
gets(mid);
out(pre,mid);
return 0;
}