最后一个测试点段错误!
错误代码:
注意:先使用scanf,在使用fgets时,中间可以调用getchar()在输入缓冲区顺序读取一个字符。
#include<cstdio>
#include<string>
#include<stack>
#include<vector>
using namespace std;
struct TreeNode{
char data;
TreeNode * leftchild;
TreeNode * rightchild;
};
vector<char> Post;
TreeNode * Build(string PreOrder,string InOrder){
if(PreOrder.size()==0){
return NULL;
}
else{
char c=PreOrder[0];
int pos=InOrder.find(c);
TreeNode * NewNode= new TreeNode;
NewNode->data=c;
NewNode->leftchild=Build(PreOrder.substr(1,pos),InOrder.substr(0,pos));
NewNode->rightchild=Build(PreOrder.substr(pos+1),InOrder.substr(pos+1));
return NewNode;
}
}
void PostOrder(TreeNode * root){
if(root==NULL){
return;
}
else{
PostOrder(root->leftchild);
PostOrder(root->rightchild);
Post.push_back(root->data);
}
}
int main(){
stack<char> mystack;
char PreO[1000]={0};
char InO[1000]={0};
int N;
scanf("%d",&N);
getchar();
int j=0,k=0;
for(int i=0;i<2*N;i++){
char arr[200];
fgets(arr,200,stdin);
string str=arr;
if(str[1]=='u'){
PreO[j]=str[5];
j++;
mystack.push(str[5]);
}
else{
InO[k]=mystack.top();
k++;
mystack.pop();
}
}
string PreOrder=PreO;
string InOrder=InO;
TreeNode * root=Build(PreOrder,InOrder);
PostOrder(root);
for(int i=0;i<Post.size()-1;i++){
printf("%c ",Post[i]);
}
printf("%c",Post[Post.size()-1]);
printf("\n");
getchar();
getchar();
return 0;
}
和A1020一样,换用vector向量存储先序和中序序列,就没有段错误了。
注意:
char arr[10];
fgets(arr,10,stdin);
getchar();
if(arr[1]=='u'){
a=arr[5]-'0';
使用上面的写法,最后一个测试点总是错误!
char arr[10];
scanf("%s",arr);
getchar();
if(arr[1]=='u'){
scanf("%d",&a);
正确代码:
#include<cstdio>
#include<vector>
#include<string>
#include<stack>
using namespace std;
struct TreeNode{
int data;
TreeNode * leftchild;
TreeNode * rightchild;
};
vector<int> Pre;
vector<int> In;
vector<int> Post;
TreeNode * Build(int Preleft,int Preright,int Inleft,int Inright){
if(Preleft > Preright || Inleft > Inright){
return NULL;
}
else{
int pos;
int cdata=Pre[Preleft];
for(int i=Inleft;i<=Inright;i++){
if(cdata==In[i]){
pos=i;
break;
}
}
TreeNode * root=new TreeNode;
root->data=cdata;
int length1=pos-Inleft;
int length2=Inright-pos;
root->leftchild=Build(Preleft+1,Preleft+length1,Inleft,pos-1);
root->rightchild=Build(Preright-length2+1,Preright,pos+1,Inright);
return root;
}
}
void PostOrder(TreeNode * root,vector<int> & Post){
if(root==NULL){
return;
}
else{
PostOrder(root->leftchild,Post);
PostOrder(root->rightchild,Post);
Post.push_back(root->data);
}
}
int main(){
int N;
scanf("%d",&N);
getchar();
stack<int> mystack;
int a,b;
for(int i=0;i<2*N;i++){
char arr[10];
scanf("%s",arr);
getchar();
if(arr[1]=='u'){
scanf("%d",&a);
Pre.push_back(a);
mystack.push(a);
}
else{
b=mystack.top();
mystack.pop();
In.push_back(b);
}
}
TreeNode * root=Build(0,Pre.size()-1,0,In.size()-1);
PostOrder(root,Post);
for(int i=0;i<Post.size();i++){
if(i!=0)
printf(" ");
printf("%d",Post[i]);
}
printf("\n");
getchar();
getchar();
return 0;
}