递归经典 后序+中序 输出树的先序遍历

来源:互联网 发布:seo和sem的区别 编辑:程序博客网 时间:2024/04/30 20:24

//从后序和中序的顺序中 转换成树的先序输出
//无比经典,自己写的递归程序
//用到了数据结构和递归程序
//string的构造函数 string(str,org,length) 注意第三个参数是从org开始数几个字符长
//还有这种函数 用传root的方法比较清楚

#include <string>
#include <cstdio>
#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct TREE
{
 string str;
 TREE* lefttree;
 TREE* righttree;
 TREE(string aa){ str=aa;lefttree=NULL;righttree=NULL; }
} tree;


void display(TREE* r)

 if(r==NULL)
  return ;
 cout<<r->str;
 display(r->lefttree);
 display(r->righttree);
}

void clear(TREE* r)
{
 if(r==NULL)
  return ;
 clear(r->lefttree);
 clear(r->righttree);
 delete r;
}


void buildtree(string mid,string post,tree* tr)     //mid是中序,post是后序字符串,tr中是中序的字符串
{
 
 if( mid.length()==1 )
  return ;

 int left=mid.find( post[post.length()-1] );
 int right=left+1;
 
 string ll( mid,0,left );
 string rr( mid,right); //应该是到底

 string t1(post,0,ll.length());
 string t2(post,ll.length(),post.length()-1-ll.length());

 tree* ltr=new tree(ll);
 tree* rtr=new tree(rr);
 tr->str=post[post.length()-1];
 tr->lefttree=ltr;
 tr->righttree=rtr;


 buildtree( ll,t1,ltr );
 buildtree( rr,t2,rtr );
}

 

 

int main()
{
 tree* root=new tree(string("HDIBJEKAMFNCOGP"));
 string mm("HDIBJEKAMFNCOGP");
 string pp("HIDJKEBMNFOPGCA");
 

 buildtree(mm,pp,root);
 display(root);
 cout<<endl;
 clear(root);

 getchar();
 return 0;
}

原创粉丝点击