这道题快把我弄晕了。。我讨厌各种序结合建树嘤嘤嘤。。。
先序第一个肯定是根,第二个是左子树或者右子树的根pre[preL] -> 在后序序列找到该点划分左右子树,然后计算个数,递归。(看了一下别人的思路写的)
#include<cstdio>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
int n;
vector<int> pre,post,in;
bool unq=false;
struct node{
int sq;
node* lchild;
node* rchild;
};
node* create(int preL,int preR,int postL,int postR){
if(preL>preR){
unq=true;
return NULL;
}
node* root=new node;
root->sq=pre[preL];
if(preL==preR){
root->lchild=NULL;
root->rchild=NULL;
return root;
}
int i=preL+1;
int j=postL;
if(i<=preR){
for(j=postL;j<=postR;j++){
if(pre[i]==post[j]) break;
}
}
int numleft=j-postL;
root->lchild=create(i,i+numleft,postL,j);
root->rchild=create(i+numleft+1,preR,j+1,postR-1);
return root;
}
void inorder(node* root){
if(root->lchild!=NULL) inorder(root->lchild);
in.push_back(root->sq);
if(root->rchild!=NULL) inorder(root->rchild);
}
int main(){
scanf("%d",&n);
int i,temp;
for(i=0;i<n;i++){
scanf("%d",&temp);
pre.push_back(temp);
}
for(i=0;i<n;i++){
scanf("%d",&temp);
post.push_back(temp);
}
node* root=create(0,n-1,0,n-1);
inorder(root);
if(unq==true) printf("No\n");
else printf("Yes\n");
for(i=0;i<n;i++){
if(i<n-1) printf("%d ",in[i]);
else printf("%d\n",in[i]);
}
system("pause");
return 0;
}