栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

PAT-A 1086 Tree Traversals Again (25 分)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 

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 <data;
        if(num!=n)
        cout <<" ";
    }
}
int main()
{
    cin >> n;
    cin >>s;
    struct node*root=NULL;
    create(root);
    houxv(root);
    
    
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630485.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号