PAT-A 1086 Tree Traversals Again (25 分)

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

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

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

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

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

在这里插入图片描述

输入格式
第一行包含整数 N,表示树中节点个数。

树中节点编号从 1 到 N。

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

Push X,将编号为 X 的节点压入栈中。
Pop,弹出栈顶元素。
输出格式
输出这个二叉树的后序遍历序列。

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

数据范围
1≤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

可以看作Push即有相应的孩子,Pop则相应孩子为空

#include <bits/stdc++.h>

using namespace std;
struct node
{
    int data;
    struct node*l,*r;
};
string s;
int n;
int num=0;
void create(struct node*&root)
{
    int shu;
    cin >>shu;
    root = new node;
    root->data=shu;
    cin >>s;
    if(s=="Push")
    create(root->l);
    else
    root->l=NULL;
    
    cin >> s;
    if(s=="Push")
   create(root->r);
   else
   root->r=NULL;
}
void houxv(struct node*root)
{
    if(root)
    {
        houxv(root->l);
        houxv(root->r);
        num++;
        cout <<root->data;
        if(num!=n)
        cout <<" ";
    }
}
int main()
{
    cin >> n;
    cin >>s;
    struct node*root=NULL;
    create(root);
    houxv(root);
    
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值