PAT A1086 Tree Traversals Again

来源:互联网 发布:money for mac 破解版 编辑:程序博客网 时间:2024/05/11 18:00
//最后一个测试点答案错误,不知道错在哪里了,4分 //又忘记了using namespace std; //用scanf()根本不需要清空!直接每次scanf()就行了//用string好清空。注意string一定要用cin输入! #include<cstdio>#include<cstring>#include<stack>#include<string>//#include<iostream>//#define LOCALusing namespace std;int inorder[30];int preorder[30]; int n;//n<=30 struct node{int data;node* lchild;node* rchild;};node* create(int preL,int preR,int inL,int inR){if(preL>preR){return NULL;//如果先序序列中为空,说明结束了 }node* root=new node();root->data=preorder[preL];int k;for(k=inL;k<=inR;k++){if(preorder[preL]==inorder[k])break;}int numleft=k-inL;root->lchild=create(preL+1,preL+numleft,inL,k-1);root->rchild=create(preL+numleft+1,preR,k+1,inR);return root;}int count=0;void postorder(node* root){if(root==NULL){return;}if(root->lchild!=NULL) postorder(root->lchild);if(root->rchild!=NULL) postorder(root->rchild);printf("%d",root->data);if(++count!=n) printf(" "); }int main(){#ifdef LOCALfreopen("A1086.in","r",stdin);freopen("A1086.out","w",stdout);#endif scanf("%d",&n);getchar();//一定这里记得去掉空格 stack<int> s;//string str;char str[10];int num=0,numpre=0;while(!s.empty()){s.pop();}for(int i=0;i<2*n;i++){//gets(str);//cin>>str;gets(str);if(str[1]=='u'){int m=str[5]-'0';s.push(m);preorder[numpre++]=m;}else{if(!s.empty()){inorder[num++]=s.top();s.pop();} }//str.clear();//getchar();用gets()时\n变成了\0,缓冲区也没有了 }node* root=create(0,n-1,0,n-1);postorder(root);return 0;} 

0 0