PAT 1119. Pre- and Post-order Traversals (30)
阿新 • • 發佈:2018-11-20
#include<iostream> #include<cstring> #include<cstdio> #include<cstdlib> using namespace std; int n,pre[35],post[35],flag=0; int ans[35],k; struct node{ int num; struct node* left; struct node* right; }; struct node* build(struct node* t,int preleft,int preright,int postleft,int postright){ // cout<<preleft<<' '<<preright<<' '<<postleft<<' '<<postright<<endl; if((postright-postleft)!=(preright-preleft)) return t; if((postright<postleft)||(preright<preleft)) return t; // if(postright>n||postleft<0||preright>n||preleft<0) return t; if(t==NULL){ struct node* p=(struct node*)malloc(sizeof(struct node)); if(p==NULL) return p; p->num=pre[preleft]; p->left=NULL; p->right=NULL; t=p; // free(p); } if(preleft<preright){ int len=0,mid,i; for(i=postleft;i<postright;i++){ if(post[i]==pre[preleft+1]){ break; } } len=i+1-postleft; t->left=build(t->left,preleft+1,preleft+len,postleft,i); len=postright-(i+1); t->right=build(t->right,preright-len+1,preright,i+1,postright-1); } return t; } int level(struct node* t){ // cout<<t<<endl; if(t==NULL) return 0; if((t->left!=NULL&&t->right==NULL)||(t->left==NULL&&t->right!=NULL)){ // cout<<"No"<<endl; flag=1; } if(t->left!=NULL){ level(t->left); } // cout<<t->num<<' '; ans[k++]=t->num; if(t->right!=NULL){ level(t->right); } return 0; } int main(){ int n; flag=0; cin>>n; for(int i=0;i<n;i++){ cin>>pre[i]; } for(int i=0;i<n;i++){ cin>>post[i]; } struct node* t; t=NULL; t=build(t,0,n-1,0,n-1); level(t); if(flag){ cout<<"No"<<endl; cout<<ans[0]; for(int i=1;i<k;i++){ cout<<" "<<ans[i]; } cout<<endl; } else{ cout<<"Yes"<<endl; cout<<ans[0]; for(int i=1;i<k;i++){ cout<<" "<<ans[i]; } cout<<endl; } return 0; }