【数据结构与算法】2.5 Tree Traversals Again

在这里插入图片描述

在这里插入图片描述

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值