再次树遍历

1576. 再次树遍历

通过使用栈可以以非递归方式实现二叉树的中序遍历。

例如,假设遍历一个如下图所示的 66 节点的二叉树(节点编号从 11 到 66)。

则堆栈操作为:push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop()。

我们可以从此操作序列中生成唯一的二叉树。

你的任务是给出这棵树的后序遍历。

3.png

输入格式

第一行包含整数 NN,表示树中节点个数。

树中节点编号从 11 到 NN。

接下来 2N2N 行,每行包含一个栈操作,格式为:

  • Push X,将编号为 XX 的节点压入栈中。
  • Pop,弹出栈顶元素。
输出格式

输出这个二叉树的后序遍历序列。

数据保证有解,数和数之间用空格隔开,末尾不能有多余空格。

数据范围

1≤N≤301≤N≤30

输入样例:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
输出样例:
3 4 2 6 5 1

#include <iostream>
#include <stack>
#include <vector>
#include <map>
using namespace std;
const int  N=40;
int preorder[N],inorder[N], j,k;
int postorder[N];
map<int,int>pos,l,r;
int cnt;
int build(int pl,int pr,int il,int ir)
{
    if(il>ir)   return 0;
    int root=preorder[pl];
    int key=pos[root];
    if(il<key)  l[root]=    build(pl+1,pl+key-il,il,key-1);
    if(ir>key)  r[root]=    build(pl+key-il+1,pr,key+1,ir);
    return root;
}
void  post(int root)
{
    if(l[root]) post(l[root]);
    if(r[root]) post(r[root]);
     postorder[cnt++]=root;

}
int main()
{
    int n;
    stack<int>stk;
    cin>>n;
    
    for(int i=0;i<2*n;i++)
    {
    
        string s;
        cin>>s;
        if(s=="Push")
        {
            int a;
            cin>>a;
            stk.push(a);
            preorder[j++]=a;
        }
        else
        {
            inorder[k++]=stk.top();
            stk.pop();
        }
    }
    for(int i=0;i<n;i++)    pos[inorder[i]]=i;
    
   int root= build(0,j-1,0,k-1);
   post(root);
    cout<<postorder[0];
    for(int i=1;i<n;i++)    cout<<" "<<postorder[i];
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值