这个提还好,我一开始用的静态的,结果发现不太会用。。改成了链表还好。
最后输出654321我死活找不到问题,结果发现是post函数l和r写反了。。。。。
#include<bits/stdc++.h>
using namespace std;
struct node {
int data;
node* lchild;
node* rchild;
};
int inorder[31];
int preorder[31];
int postorder[31];
node *create(int a,int b,int c,int d ){
if(a>b) return NULL;
int root=preorder[a];
int n=c;
while(inorder[n]!=root)n++;
node * rt=new node;
rt->data=root;
// printf("%d\n",root);
rt->lchild=create(a+1,a+n-c,c,n-1);
rt->rchild=create(a+n-c+1,b,n+1,d);
return rt;
}
int step=1;
void post(node*root){
if(root->lchild!=NULL)post(root->lchild);
if(root->rchild!=NULL)post(root->rchild);
postorder[step++]=root->data;
}
int main(){
node *root;
stack <int> q;
int n,count1 =1,count2=1;
scanf("%d",&n);
string temp;
for(int i=0;i<2*n;i++){
cin>>temp;
if(temp=="Push"){
cin>>preorder[count1];
q.push(preorder[count1]);
count1++;
}
else{
inorder[count2]=q.top();
count2++;
q.pop();
}
}
root=create(1,n,1,n);
post(root);
for(int i=1;i<=n;i++){
printf("%d",postorder[i]);
if(i!=n)printf(" ");
}
}