#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int post[35],in[35];
typedef struct node * Tree;
struct node{
struct node *left,*right;
int data;
};
int n;
void level(Tree t){
queue<node> q;
q.push(*t);
int cnt = 0;
while(!q.empty()){
struct node temp = q.front();
q.pop();
if(cnt == n - 1){
printf("%d\n",temp.data);
cnt++;
}
else{
printf("%d ",temp.data);
cnt++;
}
if(temp.left){
q.push(*(temp.left));
}
if(temp.right){
q.push(*(temp.right));
}
}
}
Tree build(int * in,int * post,int size){
if(size <= 0){
return NULL;
}
int i;
for(i = 0; i < size; i++){
if(*(in + i) == *(post + size - 1)){
break;
}
}
Tree temp = (node*)malloc(sizeof(struct node));
temp -> data = *(in + i);
//printf("%d ",temp -> data);
temp -> left = build(in,post,i);
temp -> right = build(in + i + 1,post + i,size - i -1);
return temp;
}
int main(void){
cin >> n;
for(int i = 0; i < n; i++){
cin >> post[i];
}
for(int i = 0; i < n; i++){
cin >> in[i];
}
Tree tree = build(in,post,n);
level(tree);
return 0;
}
L2-006. 树的遍历
最新推荐文章于 2022-04-01 20:22:58 发布