#include <iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
const int maxn = 30;
int n;
int postOrd[maxn + 5], inOrd[maxn + 5];
vector<int> layer[30];
struct node{
int data;
node* left;
node* right;
};
//由後序遍歷和中序遍歷建樹
node* create(int postL, int postR, int inL, int inR, int deep){
//邊界條件,不存在該後序遍歷序列,退出
if(postL > postR) return NULL;
//創建新節點並賦值
node* root = new node;
root->data = postOrd[postR];//後序遍歷最後一個數是根節點
//找到中序序列中該根節點的下標並保存在k中
layer[deep].push_back(postOrd[postR]);
int k;
for(int i = 0; i < n; i++){
if(inOrd[i] == postOrd[postR]){
k = i;
break;
}
}
//左子樹節點個數爲k-inL,分別求該節點的左兒子和右兒子..
int numLeft = k - inL;
root->left = create(postL, postL+numLeft - 1, inL, k-1, deep+1);
root->right = create(postL+numLeft, postR-1, k+1, inR, deep+1);
return root;
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &postOrd[i]);
}
for(int i = 0; i < n; i++){
scanf("%d", &inOrd[i]);
}
node* root = create(0, n-1, 0, n-1, 1);
int flag = 0;
for(int i = 1; i <30; i++){
int len = layer[i].size();
for(int j = 0; j < len; j++){
if(flag) printf(" ");
printf("%d", layer[i][j]);
flag = 1;
}
}
return 0;
}
PAT甲級 1020 Tree Traversals(二叉樹的遍歷與建樹)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.