Q:已知二叉樹的先序和中序遍歷,求后序遍歷= =
分析:先舉個栗子,比如我們知道某二叉樹的先序遍歷和后序遍歷分別為 DBACEGF ABCDEFG,辣么如果要求后序遍歷的話,應該現在先序遍歷中找出二叉樹的根節點(也就是先序中的第一個值D),然后在去中序遍歷中找到根節點,那么就很明確的知道中序中,根節點的左邊為左子樹,右邊為右子樹,然后找出左子樹的后序遍歷和右子樹的后序遍歷,最終拼接在一起就OK了= =
參考代碼:
#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<string>#include<algorithm>#include<stack>#include<queue>#include<map>#include<iostream>using namespace std;const int maxn = 1000+10;char PRe[maxn],in[maxn];char post[maxn];//結果串int cur;void topost( char pre[], char in[],char post[], int l){ if( l <= 0) return; int i; for( i = 0; i < l; i++) if( in[i] == pre[0])//先序遍歷的第1個點(根節點) 與 中序遍歷第i+1個點的值相等 break; //所得的i為根節點在中序遍歷中的位置 同時也為后序遍歷中的最后一個 post[l-1] = pre[0]; topost( pre+1,in,post,i);//左子樹后序遍歷的轉化 topost( pre+1+i,in+i+1,post+i,l-1-i);}int main(){ while( ~scanf("%s%s",pre,in))//輸入先序 和中序遍歷 { //printf("%s %s/n",str1,str2); int len = strlen(pre);//計算計算二叉樹結點數 topost( pre,in,post,len);//轉化后序遍歷 for( int i = 0; i < len; i++)//輸出后序遍歷 putchar(post[i]); putchar(10); } return 0;}
新聞熱點
疑難解答