#include<iostream>
#include<vector>
using namespace std;
struct node{
int v;
node *L, *R;
};
vector<int> in, pre, post;
node* create(int preL, int preR, int inL, int inR){
if(preL > preR){
return NULL;
}
node *root = new node;
int k;
for(k = inL; k <= inR; k++){
if(in[k] == pre[preL]){
break;
}
}
int num = k - inL;
root->v = in[k];
root->L = create(preL+1, preL + num, inL, k - 1);
root->R = create(preL + num + 1, preR, k + 1, inR);
return root;
}
void postorder(node *root){
if(root == NULL){
return;
}
postorder(root->L);
postorder(root->R);
post.push_back(root->v);
}
int main(){
int n, num;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &num);
pre.push_back(num);
}
for(int i = 0; i < n; i++){
scanf("%d", &num);
in.push_back(num);
}
node *root = create(0, n-1, 0, n-1);
postorder(root);
printf("%d", post[0]);
return 0;
}
A 1138 Postorder Traversal (25分)(二叉树知道先序、中序遍历推后序遍历)
原文:https://www.cnblogs.com/tsruixi/p/13154828.html