#include<iostream> #include<algorithm> #include<string> #include<stack> using namespace std; typedef struct TreeNode { int data; struct TreeNode *left,*right; } TreeNode; TreeNode *pTree = new TreeNode; int n,b=0,b2=0,p,op=0; stack<int> s; int arr_pre[40],arr_mid[40],r[40],h=0; void last_order(TreeNode * Tree){ if(Tree!=NULL){ last_order(Tree->left); last_order(Tree->right); r[h++]=Tree->data; } return; } void Build_Tree(TreeNode* &Tree,int p1/* 中序遍历扫描起点 */,int p2 /* 中序遍历扫描终点 */){ if(p1>p2) return; Tree = new TreeNode; Tree->left = Tree->right = NULL; int pos; for(int i=p1;i<=p2;i++){ if(arr_mid[i]==arr_pre[op]) { pos=i; break; } } Tree->data=arr_pre[op++]; Build_Tree(Tree->left,p1,pos-1); Build_Tree(Tree->right,pos+1,p2); //cout<<Tree->data<<"| "; return; } int main(){ string act; cin>>n; pTree->left=pTree->right=NULL; while(cin>>act){ if(act=="Push"){ cin>>p; s.push(p); arr_pre[b++]=p; } if(act=="Pop"){ arr_mid[b2++]=s.top(); s.pop(); } } Build_Tree(pTree,0,n-1); last_order(pTree); for(int i=0;i<h-1;i++) cout<< r[i] <<" "; cout<<r[h-1]<<endl; return 0; }
9 total views, 9 views today