Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
思路
我们通过观察发现出栈的序列为 3 2 4 1 6 5 前序遍历
入栈顺序为 1 2 3 4 5 6 中序遍历
题目想让我们输出后序遍历的结果
到这里本题就十分明了了
由前序遍历和中序遍历求解后序遍历
前序遍历的特点是,第一个是根结点先输出,利用这个特性我们可以在中序遍历中确定根结点所在位置,进而确定出其左子树和右子树的范围,然后我们再分别对左右子树进行类似的处理
#include<bits/stdc++.h>
using namespace std;
int cnt=0,n;
stack<int>s;
vector<int>pre,in;
void travel(int root,int l,int r)
{
if(l>r)return ;
int i=l;
while(i<=r&&in[i]!=pre[root])i++;
travel(root+1,l,i-1);
travel(root+1+i-l,i+1,r);
if(cnt==n-1)
cout<<pre[root];
else cout<<pre[root]<<" ";
cnt++;
}
int main()
{
cin>>n;
getchar();
for(int i=0;i<2*n;i++)
{
string tmp;
cin>>tmp;
if(tmp=="Push")
{
int num;
cin>>num;
s.push(num);
pre.push_back(num);
}
if(tmp=="Pop")
{
in.push_back(s.top());
s.pop();
}
}
travel(0,0,n-1);
return 0;
}