一道给出前序和中序遍历的结果,重构二叉树并返回后序遍历的结果。
需要主要的地方是好好理解题目意思
#include<cstdio>
#include<cstring>
#include<vector>
#include<stack>
#include<iostream>
using namespace std;
vector<int> pre,in,post;
struct node{
int value;
node *left,*right;
node(int x):value(x),left(NULL),right(NULL){}
};
void create(node* &root, int preL,int preR, int inL, int inR){
if(preL > preR) return;
root = new node(pre[preL]);
int k=inL;
while(in[k] != pre[preL]){
k++;
}
int left = k -inL;
create(root->left, preL+1, preL+left,inL, k -1);
create(root->right, preL+left+1, preR,k+1, inR);
}
void postorder(node* root){
if(root == NULL) return;
postorder(root->left);
postorder(root->right);
post.push_back(root->value);
}
int main(){
int n,v;
char op[10];
stack<int> st;
node* root=NULL;
scanf("%d",&n);
for(int i=0;i<2*n;i++){
scanf("%s",op);
if(strcmp(op,"Push")==0){
scanf("%d",&v);
st.push(v);
pre.push_back(v);
}else{
in.push_back(st.top());
st.pop();
}
}
create(root,0,pre.size()-1, 0, in.size()-1);
postorder(root);
for(int i=0;i<post.size();i++){
if(i>0) printf(" ");
printf("%d",post[i]);
}
return 0;
}