分析:刚开始做这道题的时候一头雾水,只看出来样例这个出栈序列是中序遍历,我寻思着根据中序遍历求后序遍历吗?后来看了一下网上别人的思路才明白少考虑了个东西。仔细观察可以发现push的数是图中这个树的前序遍历,而pop的数是图中这个树的中序遍历的序列。也就是说进栈序列为前序遍历序列,出栈序列是中序遍历序列。也就是所谓的根据前序遍历和中序遍历求后序遍历,不会的同学可以看一下我这篇博客前序,中序,后序三种遍历的相互转化(思路+递归实现代码)【全】
思路:根据上面分析,我们可以建立一个栈来模拟。然后建立两个数组(in,pre)来接受两个序列
1.如果接受到push 就进栈,然后将这个数存到前序遍历数组中(pre)
2.如果接受到pop 就出栈,然后将这个数存到中序遍历数组中(in)
3.输入数据接受完之后我们就得到了两个序列,然后就是 前序+中序->后序
(可以看上面给的那个链接或者下面的代码)
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n,x,flag;
vector<int>in,pre;
char str[5];
stack<int>s;
void post(int root,int start,int end)
{
if(start>end) return ;
int i=start;
while(i<=end&&in[i]!=pre[root]) i++;
post(root+1,start,i-1);
post(root+1+i-start,i+1,end);
if(flag) cout<<" "<<pre[root];
else {cout<<pre[root]; flag=1;}
}
int main()
{
cin>>n;
for(int i=0;i<2*n;i++)
{
cin>>str;
if(!strcmp("Push",str))
{
cin>>x;
s.push(x);
pre.push_back(x);
}
else
{
in.push_back(s.top());
s.pop();
}
}
post(0,0,n-1);
}