题目链接:1020 Tree Traversals
#include <iostream>
#include <queue>
using namespace std;
int pivot;
struct node{
int val;
node *lchild, *rchild;
};
node* beTree(int po[], int io[], int low, int hign){//递归构建树
node *p = new node{po[pivot],NULL,NULL};//将后序最后一个数作为头节点
pivot--;
if(low != hign){
int temp = low;
while(io[temp] != po[pivot + 1]) temp++;//以pivot为轴分为左右子树
if(temp != hign) p->rchild = beTree(po, io, temp + 1, hign);//构建左子树
if(temp != low) p->lchild = beTree(po, io, low, temp - 1);//构建右子树
}
return p;
}
int main(){
int n;
cin >> n;
pivot = n - 1;
int order[2][n];
for(int i = 0; i < 2; i++){
for(int j = 0; j < n; j++) scanf("%d", &order[i][j]);
}
node *p = beTree(order[0], order[1], 0, n-1);
//层次遍历
queue<node*> Q;
Q.push(p);
while(!Q.empty()){
p = Q.front();
printf("%d", p->val);
if(p->lchild) Q.push(p->lchild);
if(p->rchild) Q.push(p->rchild);
Q.pop();
if(!Q.empty()) printf(" ");
}
}