#include"iostream" #include"queue" using namespace std; int x[1000],z[1000]; struct Tree{ int data; Tree *left,*right; }; void xzCreate(Tree* &t,int xl,int zl,int len){ //xl:先序起始下標,zl:中序起始下標,len:數組長度 //cout<<"zl:"<<zl<<ends<<"xl:"<<xl<<ends<<"len:"<<len<<endl; if(len == 1){ t = new Tree; t->data = z[zl]; t->left = NULL; t->right = NULL; return ; } for(int i = 0;z[i + zl] != x[xl];i++); //首先在中序中找到根結點,先序第一個結點就是根結點,所以有z[i + zl] != x[xl] if(i >= len){ //遍歷完數組還沒找到根結點,就是輸入錯誤直接返回 return ; } //創建根節點 t = new Tree; t->data = z[i + zl]; t->left = NULL; t->right = NULL; int lenl = i; //左子樹長度就是i遍歷的長度 int lenr = len - lenl - 1; //右子樹長度為 : 總長度 - 左子樹長度 - 根結點 //中序的左子樹起點從最左開始,所以還是它本身 xl = xl + 1; //先序中:左子樹起點 = 右子樹起點 + 根結點, 跳過根節點即是左子樹起點 int zr = lenl + zl + 1; //中序中:右子樹起點 = 左子樹起點 + 左子樹長度 + 根結點 int xr = xl + lenl; //先序中:右子樹起點 = 左子樹起點 + 左子樹長度 //cout<<"lenl:"<<lenl<<ends<<"lenr:"<<lenr<<ends<<"zl:"<<zl<<ends<<"xl:"<<xl<<ends<<"zr:"<<zr<<ends<<"xr:"<<xr<<endl; //遞歸建樹 if(lenl != 0){ xzCreate(t->left,xl,zl,lenl); } if(lenr != 0){ xzCreate(t->right,xr,zr,lenr); } } void show(Tree* &t){ if(t){ cout<<t->data<<ends; show(t->left); show(t->right); } } //層次遍歷 void sqshow(Tree *t){ queue<Tree*> q; Tree *p = t; q.push(p); while(!q.empty()){ p = q.front(); cout<<p->data<<ends; if(p->left){ q.push(p->left); } if(p->right){ q.push(p->right); } q.pop(); } cout<<endl; } int main(){ Tree *t; int num = 7; for(int i = 0;i < num;i++){ cin>>x[i]; } for(i = 0;i < num;i++){ cin>>z[i]; } xzCreate(t,0,0,num); sqshow(t); return 0; } /* 1 2 4 5 3 6 7 4 2 5 1 6 3 7 */