1. 程式人生 > >POJ2255-已知二叉樹前序中序求後序

POJ2255-已知二叉樹前序中序求後序

nbsp def 二叉樹 水題 輸出 ostream -i sin root

水題……也可以不建立二叉樹來做

如果pre[pl:pr]對應in[il:ir],那麽pre[pl]是這棵樹的根,它在in的位置記為root,顯然root在[il,ir]內

那麽二叉樹的左子樹是in[il:root-1],也即pre[pl+1:pl+root-il]

二叉樹的右子樹是in[root+1,ir],也即pre[pl+root-il+1:pr]

按照左子樹-右子樹-樹根的後序遍歷方式輸出即可

附代碼

技術分享
#include <string>
#include <iostream>
#include <algorithm>
#define MAX 1000007
#define
MAXN 1007 using namespace std; int pre[MAXN],in[MAXN]; void getpost(int prel,int prer,int inl,int inr){ //if(prel>prer||inl>inr) return; int root=inl;//root是先序的第一個節點在中序的位置 while(in[root]!=pre[prel]) root++; if(root!=inl) getpost(prel+1,prel+root-inl,inl,root-1); if(root!=inr) getpost(prel+root-inl+1
,prer,root+1,inr); printf("%c",pre[prel]); } int main(){ string a,b; while(cin>>a>>b){ int len=a.length(); for(int i=0;i<len;i++){ pre[i]=a[i]; in[i]=b[i]; } getpost(0,len-1,0,len-1); printf("\n"); } return
0; } /* DBACEGF ABCDEFG BCAD CBAD */
View Code

POJ2255-已知二叉樹前序中序求後序