push顺序给出先序遍历,pop顺序给出中序遍历,根据先序中序直接求出后序,并不需要构建图
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<map>
#include<vector>
#include<cstring>
#include<math.h>
#include<stack>
using namespace std;
int N;
int pre[100],in[100],post[100];
void solve(int prel,int inl,int postl,int n)//PreL代表从PreOrder当前第一个节点的位置,InL,PostL同理。n代表传入的规模
{
if(n==0) return;
if(n==1) { post[postl] = pre[prel]; return; }
int root = pre[prel]; //找出当前的根节点
post[postl+n-1] = root;//把根节点插入到后序遍历的数组中
int i;
for( i=0;i<n;i++) //找到在中序遍历数组中此时root位置
if(in[inl+i] == root) break;
int L=i; //L表示此时root左边节点个数
int R=n-L-1; //R表示此时root右边节点个数
solve(prel+1, inl,postl,L); //分而治之,对左子树递归
solve(prel+L+1,inl+L+1,postl+L,R); //对右子树递归
}
int main()
{
cin>>N;
int x,npre=0,nin=0;
string ss;
stack<int >st;
while(1)
{
cin>>ss;
if(ss[1]=='u')
{
cin>>x;
st.push(x);
pre[npre++]=x;
getchar();
}
else if(ss[1]=='o')
{
x=st.top();
st.pop();
in[nin++]=x;
getchar();
}
if(npre==N&&nin==N)
break;
}
solve(0,0,0,N);
for(int i=0;i<N;i++)
{
if(i>0)
cout<<" ";
cout<<post[i];
}
}