例子,后序遍历为 gbdehfca,中序遍历为 dgbaechf
后序遍历中的最后一个元素是根节点,a,然后查找中序中a的位置
把中序遍历分成 dgb a echf,而因为节点个数要对应
后序遍历分为 gbd ehfc a,gbd为左子树,ehfc为右子树,这样又可以递归计算了
最后形成的二叉树如下图片所示:
具体代码如下:
递归:
- #include<iostream.h>
- #include<string.h>
- #include<stdlib.h>
- #define MAX 20 /*预定义字符数组的最大长度*/
- typedef struct tnode /*该结构体类型为树结点的类型*/
- {
- char data;
- struct tnode *lchild;
- struct tnode *rchild;
- } *bt;
- void in_post_to_bt(char *in,char *post,int len,bt &T) /*由长度为len的中序序列in和后序序列post唯一确定一棵二叉树T*/
- {
- int k;
- if(len<=0)
- {
- T=NULL;
- return;
- }
- for(char *temp=in;temp<in+len;temp++) /*在中序序列in中找到根节点所在的位置*/
- if(*(post+len-1)==*temp)
- {
- k=temp-in; /*k为根结点在中序序列中的下标*/
- T=(bt)malloc(sizeof(struct tnode));
- T->data =*temp;
- break;
- }
- in_post_to_bt(in,post,k,T->lchild ); /*建立左子树*/
- in_post_to_bt(in+k+1,post+k,len-k-1,T->rchild ); /*建立右子树*/
- }
- void in_visit(bt T)/*中序遍历树T*/
- {
- if(T)
- {
- in_visit(T->lchild );
- cout<<T->data ;
- in_visit(T->rchild );
- }
- }
- void post_visit(bt T)/*后序遍历树*/
- {
- if(T)
- {
- post_visit(T->lchild );
- post_visit(T->rchild );
- cout<<T->data ;
- }
- }
- main()
- {
- char in[MAX+1],post[MAX+1];
- cout<<"输入中序序列:";
- cin>>in;
- cout<<"输入后序序列:";
- cin>>post;
- bt T;
- int len_in=strlen(in),len_post=strlen(post);
- if(len_in<=MAX&&len_post<=MAX)
- in_post_to_bt(in,post,len_in,T);
- cout<<endl<<"输出中序序列:";
- in_visit(T);
- cout<<endl<<"输出后序序列:";
- post_visit(T);
- cout<<endl;
- }
原文地址:http://blog.csdn.net/wuchuanpingstone/article/details/6860453