二叉树的构造

来源:互联网 发布:python中sleep函数 编辑:程序博客网 时间:2024/04/26 05:41

      我们假设二叉树中每个节点的值都不相同,那么二叉树具有唯一的先序序列、中序序列、后序序列(注意不同的二叉树可能有相同的先序、中序、后序序列)。引入如下两个定理(数学归纳法很容易可以证明,这里不给出证明):

1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和先序序列唯一确定。

1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和后序序列唯一确定。

给出二叉树的两个序列,返回出二叉树的根结点,代码如下:

/*Author:IbsenDate:2015.12.15*/#include <iostream>using namespace std;const int M=1000;typedef struct node{char data;struct node *lc,*rc;}BTree;BTree* Creat_BTree_pre_in(char *pre,char *in,int n){BTree *h;char *p;if(n<=0) return NULL;h=new BTree();h->data=*pre;for(p=in;p<in+n;p++)if(*p==*pre) break;int pos=p-in;h->lc=Creat_BTree_pre_in(pre+1,in,pos);h->rc=Creat_BTree_pre_in(pre+1+pos,p+1,n-1-pos);return h;}BTree* Creat_BTree_in_post(char *in,char *post,int n){BTree *h;char *p;if(n<=0) return NULL;h=new BTree();h->data=*(post+n-1);for(p=in;p<in+n;p++)if(*p==h->data) break;int pos=p-in;h->lc=Creat_BTree_in_post(in,post,pos);h->rc=Creat_BTree_in_post(p+1,post+pos,n-1-pos);return h;}void Display_BTree(BTree *h){if(h!=NULL){cout<<h->data;if(h->lc!=NULL||h->rc!=NULL){cout<<"(";Display_BTree(h->lc);if(h->rc!=NULL) cout<<",";Display_BTree(h->rc);cout<<")";}}}char pre[M],in[M],post[M]; //先序,中序,后序序列int main(){int n; //节点个数BTree *h;while(cin>>n){cin>>pre>>in>>post;h=Creat_BTree_pre_in(pre,in,n);Display_BTree(h);cout<<endl;h=Creat_BTree_in_post(in,post,n);Display_BTree(h);cout<<endl;}return 0;}


0 0
原创粉丝点击