topic:
analysis:
From the title analysis, a preorder traversal of the tree is the sequence of the stack, the stack is the order of the tree traversal sequence, respectively, using an array of pre, mid storage preamble and postorder result, according to the preamble and then through the results obtained subsequent to the post-order traversal
Code:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int n,ind,indx,ii;
int mid[35],pre[35];
string str;
vector<int> pos;
void PostOrder(int root,int st,int ed) //root是对于前序数组pre ,st、ed是对于中序数组 mid
{
if(st > ed) return;
int index=st;
while(st<ed&&pre[root]!=mid[index]) index++;
PostOrder(root+1,st,index-1);
PostOrder(root+1+index-st,index+1,ed);
pos.push_back(pre[root]);
}
int main()
{
int val;
stack<int> s;
scanf("%d",&n);
int tmp = 2*n;
while(tmp--)
{
cin >> str;
if(str[1]=='u')
{
scanf("%d",&val);
pre[indx++] = val; //前序
s.push(val);
}
if(str[1]=='o')
{
mid[ind++] = s.top(); //中序
s.pop();
}
}
PostOrder(0,0,n-1);
for(unsigned i=0;i<pos.size();++i)
if(i==pos.size()-1)
printf("%d\n",pos[i]);
else
printf("%d ",pos[i]);
return 0;
}