例子,後序周遊為 gbdehfca,中序周遊為 dgbaechf
後序周遊中的最後一個元素是根節點,a,然後查找中序中a的位置
把中序周遊分成 dgb a echf,而因為節點個數要對應
後序周遊分為 gbd ehfc a,gbd為左子樹,ehfc為右子樹,這樣又可以遞歸計算了
最後形成的二叉樹如下圖檔所示:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIml2Zuo3QjVzNycDM1IDOxMTMfBzLcBTMvwFMxETMwIzLcRnbl1GajFGd0F2LcRXZu5ibkN3YukGavw1LcpDc0RHaiojIsJye.gif)
具體代碼如下:
遞歸:
[cpp] view plain copy print ?
- #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)
- {
- int k;
- if(len<=0)
- {
- T=NULL;
- return;
- }
- for(char *temp=in;temp<in+len;temp++)
- if(*(post+len-1)==*temp)
- {
- k=temp-in;
- 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)
- {
- 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