// main.cpp// ProperRebuild//// Created by lip0041 on 2021/1/21.//#include<iostream>#include<cstdio>usingnamespacestd;constintMAX=4e6+10;intpre[MAX];intpost[MAX];structNode{intdata;structNode*left;structNode*right;};// 创建树structNode*buildtree(intl1,intr1,intl2,intr2){// 当前根结点structNode*root=newstructNode;root->data=pre[l1];root->left=root->right=nullptr;// p为当前根的左孩子在后序遍历中的位置intp=0;if(r2==l2)returnroot;// 找下一个左根在post中的位置for(inti=l2;i<=r2;++i)if(post[i]==pre[l1+1]){p=i;break;}// 由p将post序列分开,t为左边子树的个数intt=p-l2+1;root->left=buildtree(l1+1,l1+t,l2,p);root->right=buildtree(l1+t+1,r1,p+1,r2-1);returnroot;}// 中序遍历voidtraversal(structNode*root){if(root==nullptr)return;traversal(root->left);cout<<root->data<<" ";traversal(root->right);}intmain(){intn;cin>>n;for(inti=0;i<n;++i)cin>>pre[i];for(inti=0;i<n;++i)cin>>post[i];structNode*root=buildtree(0,n-1,0,n-1);traversal(root);return0;}