您的位置:首页 > 其它

树:(先序、中序得后序)(中序、后序得先序)递归实现

2015-07-20 10:46 260 查看
/*先序、中序  得 后序

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define N 1010

char s1
,s2
,ans
;
void build(int n,char *s1,char *s2,char *s){ //一定要传入ans,因为每次递归时ans的初始位置都会相应变化!
if(n<=0) return ;
int mid=0;
int len2 = strlen(s2);
for(int i=0;i<len2;i++){
if(s1[0]==s2[i]) {
mid = i;
break;
}
}
//找到中序中 根节点的位置mid
s[n-1] = s1[0];  //这里只是求得最后的一个序列。
build(mid,s1+1,s2,s);
build(n-mid-1,s1+1+mid,s2+1+mid,s+mid);
}
int main() {
freopen("/Users/a1/Public/20150717/20150717/in.txt","r",stdin);

while(scanf("%s %s",s1,s2)!=EOF){
int n = strlen(s1);
build(n,s1,s2,ans);
ans
= '\0';
printf("%s\n",ans);
}
return 0;
}

*/

/* */
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define N 1010

char s1
,s2
,ans
;  //后序、中序   得先序
void build(int n,char *s1,char *s2,char *s){ //一定要传入ans,因为每次递归时ans的初始位置都会相应变化!
if(n<=0) return ;
int mid=0;
int len2 = strlen(s2);
for(int i=len2-1;i>=0;i--){
if(s1[n-1]==s2[i]) {
mid = i;
break;
}
}
//找到中序中 根节点的位置mid
s[0] = s1[n-1];  //这里只是求得最后的一个序列。
build(mid,s1,s2,s+1);
build(n-mid-1,s1+mid,s2+1+mid,s+1+mid);
}
int main() {
//freopen("/Users/a1/Public/20150717/20150717/in.txt","r",stdin);

while(scanf("%s %s",s1,s2)!=EOF){
int n = strlen(s1);
build(n,s1,s2,ans);
ans
= '\0';
printf("%s\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: