下面是错误的。不能通过。原因在于if语句后面多了个分号。害的我找了一上午。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
stack<int> st;
int pre[50];
int in[50];
int num;
struct node{
int data;
node* l;
node* r;
};
node* create(int pre1,int pre2,int in1,int in2){
if(pre1>pre2){
return NULL;
}
node* root=new node;
root->data=pre[pre1];
int k;
for(k=in2;k>=in1;k--){
if(in[k]==pre[pre1]);
break;//经常在这里犯错。以为k指向根数值的前一个。导致后续出错!!!
}
root->l=create(pre1+1,pre1+k-in1,in1,k-1);
root->r=create(pre1+k-in1+1,pre2,k+1,in2);
return root;
}
int n=0;
void postorder(node* root){
if(root==NULL)
return;
postorder(root->l);
postorder(root->r);
printf("%d",root->data);
n++;
if(n<num) printf(" ");
}
int main(){
scanf("%d",&num);
char str[5];
int x,index1=0,index2=0;
for(int i=0;i<num*2;i++){
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&x);
pre[index1++]=x;
st.push(x);
}else{
in[index2++]=st.top();
st.pop();
}
}
node* root=create(0,num-1,0,num-1);
postorder(root);
return 0;
}
改正之后如下
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
stack<int> st;
int pre[50];
int in[50];
int num;
struct node{
int data;
node* l;
node* r;
};
node* create(int pre1,int pre2,int in1,int in2){
if(pre1>pre2){
return NULL;
}
node* root=new node;
root->data=pre[pre1];
int k;
for(k=in2;k>=in1;k--){
if(in[k]==pre[pre1])
break;//经常在这里犯错。以为k指向根数值的前一个。导致后续出错!!!
}
root->l=create(pre1+1,pre1+k-in1,in1,k-1);
root->r=create(pre1+k-in1+1,pre2,k+1,in2);
return root;
}
int n=0;
void postorder(node* root){
if(root==NULL)
return;
postorder(root->l);
postorder(root->r);
printf("%d",root->data);
n++;
if(n<num) printf(" ");
}
int main(){
scanf("%d",&num);
char str[5];
int x,index1=0,index2=0;
for(int i=0;i<num*2;i++){
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&x);
pre[index1++]=x;
st.push(x);
}else{
in[index2++]=st.top();
st.pop();
}
}
node* root=create(0,num-1,0,num-1);
postorder(root);
return 0;
}