我是通过建树做的,第一次在后序中找先序的preL+1,第二次在先序中找后序的postR-1,问题来了。。
第一次全部段错误。
#include<stdio.h>
int pre[35],post[35];
int n,num=0;
bool flag=true;
struct node{
int data;
node *lchild,*rchild;
};
node* create(int preL,int preR,int postL,int postR){
if(postL>postR) {
flag=false;
return NULL;
}
node* root=new node;
root->data=pre[preL];
int k;
for(k=postL;k<=postR;k++){
if(post[k]==pre[preL+1]){
break;
}
}
int num1=k-postL+1;
root->lchild=create(preL+1,preL+num1,postL,k);
root->rchild=create(preL+num1+1,preR,k+1,postR-1);
return root;
}
void inorder(node* root){
if(root==NULL) return;
inorder(root->lchild);
printf("%d",root->data);
num++;
if(num<n) printf(" ");
inorder(root->rchild);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&pre[i]);
}
for(int i=0;i<n;i++){
scanf("%d",&post[i]);
}
node* root=create(0,n-1,0,n-1);
if(flag==false){
printf("No\n");
inorder(root);
}else{
printf("Yes\n");
inorder(root);
}
printf("\n");
return 0;
}
第二次全部正确。。
#include<stdio.h>
int pre[35],post[35];
int n,num=0;
bool flag=true;
struct node{
int data;
node *lchild,*rchild;
};
node* create(int preL,int preR,int postL,int postR){
if(preL>preR) return NULL;
node* root=new node;
root->data=post[postR];
int k;
for(k=preL+1;k<=preR;k++){
if(pre[k]==post[postR-1]){
break;
}
}
if(preL+1<n&&postR-1>=0&&pre[preL+1]==post[postR-1]) flag=false;
int num1=k-preL-1;
root->lchild=create(preL+1,k-1,postL,postL+num1-1);
root->rchild=create(k,preR,postL+num1,postR-1);
return root;
}
void inorder(node* root){
if(root==NULL) return;
inorder(root->lchild);
printf("%d",root->data);
num++;
if(num<n) printf(" ");
inorder(root->rchild);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&pre[i]);
}
for(int i=0;i<n;i++){
scanf("%d",&post[i]);
}
node* root=create(0,n-1,0,n-1);
if(flag==false){
printf("No\n");
inorder(root);
}else{
printf("Yes\n");
inorder(root);
}
printf("\n");
return 0;
}