根据先序和中序遍历求后续遍历

//代码附有测试部分 可以清楚地了解到每一步的输出结果

#include <string.h>
#include <stdio.h>
/*void build(int n,char *s1,char *s2,char *s)
{
 if(n<=0)
  return;
 int p=strchr(s2,s1[0])-s2;//找到根结点在中序遍历中的位置
 build(p,s1+1,s2,s);//递归构造左子树的后序遍历
 build(n-p-1,s1+p+1,s2+p+1,s+p);//递归构造右子树的后序遍历
 s[n-1]=s1[0];//把根结点添加到最后
}*/
void build(int n, char* s1, char* s2, char* s) 
{
  if(n <= 0) return;
  int p = strchr(s2, s1[0]) - s2; 
  printf("%d\n",p);
  build(p, s1+1, s2, s);
  build(n-p-1, s1+p+1, s2+p+1, s+p);
  printf("s1[0]:%c\n",s1[0]);
  printf("s2[0]:%c\n",s2[0]);
  s[n-1] = s1[0];
}
int main()
{
 char s1[100],s2[100],ans[100];
 while(scanf("%s%s",s1,s2)==2)
 {
  int n=strlen(s1);
  build(n,s1,s2,ans);
  ans[n]='\0';
  printf("%s",ans);
 
 }
 return 0;
}
View Code

 

posted on 2013-07-09 00:40  Forgiving  阅读(158)  评论(0编辑  收藏  举报