题目描述

An inorder binary tree traversal can be implemented in a non-recursive way with a stack.  For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop().  Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations.  Your task is to give the postorder traversal sequence of this tree.


Figure 1

输入描述:

Each input file contains one test case.  For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N).  Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

输出描述:

For each test case, print the postorder traversal sequence of the corresponding tree in one line.  A solution is guaranteed to exist.  All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

输入例子:

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> using namespace std; struct Node
{
int val;
Node* l;
Node* r;
Node(int a = -) :val(a), l(nullptr), r(nullptr) {} }; //通过前序、中序构造二叉树
Node* Create(const vector<int>dataPre, const vector<int>dataOrd,
int preL, int preR, int ordL, int ordR)//数据源,前序的左右边界,中序的左右边界
{
if (preL < preR)
return nullptr;
Node* root = new Node();
root->val = dataPre[preL];//根节点
int k = ordL;
while (dataOrd[k] != dataPre[preL])
++k;
k = k - ordL;//左子树个数
root->l = Create(dataPre, dataOrd, preL + , preL + k, ordL, ordL + k - );//构造左子树
root->r = Create(dataPre, dataOrd, preL + k + , preR, ordL + k + , ordR);//构造右子树
return root;
} //后序遍历
void LastTravle(vector<int>&res, Node* root)
{
if (root == nullptr)
return;
LastTravle(res, root->l);
LastTravle(res, root->r);
res.push_back(root->val);
} int main()
{
int N;
cin >> N;
N = * N;
stack<int>data;
vector<int>dataPre, dataOrd;
while (N--)
{
string str;
cin >> str;
if (str == "Push")
{
int a;
cin >> a;
dataPre.push_back(a);
data.push(a);
}
else
{
dataOrd.push_back(data.top());
data.pop();
}
}
Node* root;
root = Create(dataPre, dataOrd, , dataPre.size() - , , dataOrd.size() - );
vector<int>res;
LastTravle(res, root);
for (int i = ; i < res.size() - ; ++i)
cout << res[i] << " ";
cout << res[res.size() - ] << endl;
}

版本二:

使用key,避免了重复数字的尴尬,也不需真正构造一颗二叉树
 #include <vector>
#include <stack>
#include <string>
using namespace std;
vector<int> pre, in, post, value;
void postorder(int root, int start, int end) {
if (start > end) return;
int i = start;
while (i < end && in[i] != pre[root]) i++;
postorder(root + , start, i - );
postorder(root + + i - start, i + , end);
post.push_back(pre[root]);
}
int main() {
int n;
cin >> n;
n = * n;
stack<int> s;
int key = ;
while (n--) {
string str;
cin >> str;
if (str.length() == ) {
int num;
cin >> num;
value.push_back(num);
pre.push_back(key);
s.push(key++);
}
else {
in.push_back(s.top());
s.pop();
}
}
postorder(, , pre.size() - );
printf("%d", value[post[]]);
for (int i = ; i < n; i++)
printf(" %d", value[post[i]]);
return ;
}

PAT甲级——【牛客练习A1004】的更多相关文章

  1. PAT甲级训练刷题代码记录

    刷题链接:https://www.patest.cn/contests/pat-a-practise 1001 #include <iostream> #include <stdio ...

  2. PAT甲级题解(慢慢刷中)

    博主欢迎转载,但请给出本文链接,我尊重你,你尊重我,谢谢~http://www.cnblogs.com/chenxiwenruo/p/6102219.html特别不喜欢那些随便转载别人的原创文章又不给 ...

  3. PAT甲级1131. Subway Map

    PAT甲级1131. Subway Map 题意: 在大城市,地铁系统对访客总是看起来很复杂.给你一些感觉,下图显示了北京地铁的地图.现在你应该帮助人们掌握你的电脑技能!鉴于您的用户的起始位置,您的任 ...

  4. PAT——甲级1009:Product of Polynomials;乙级1041:考试座位号;乙级1004:成绩排名

    题目 1009 Product of Polynomials (25 point(s)) This time, you are supposed to find A×B where A and B a ...

  5. PAT——甲级1046S:shortest Distance

    这道题,折磨了我一个多小时,前前后后写了三个算法. 1046 Shortest Distance (20 point(s)) The task is really simple: given N ex ...

  6. PAT甲级考前整理(2019年3月备考)之三,持续更新中.....

    PAT甲级考前整理一:https://www.cnblogs.com/jlyg/p/7525244.html,主要讲了131题的易错题及坑点 PAT甲级考前整理二:https://www.cnblog ...

  7. PAT甲级满分攻略|记一次考试经历

    一次考试经历 今天是"大雪",很冷. 来到隔壁的学校考试,记得上一次来河中医是两年前大一刚开学吧,那天晚上印象比较深刻,6个室友骑车到处闲逛.当时还不会Hello world. 很 ...

  8. 图论 - PAT甲级 1013 Battle Over Cities C++

    PAT甲级 1013 Battle Over Cities C++ It is vitally important to have all the cities connected by highwa ...

  9. 图论 - PAT甲级 1003 Emergency C++

    PAT甲级 1003 Emergency C++ As an emergency rescue team leader of a city, you are given a special map o ...

随机推荐

  1. 随笔-ansible-4

    触发器: 一个任务同时调用多个触发器: 为远程主机上的用户设置环境变量: 保存前一步命令的输出结果,并保存到foo中: 添加环境变量的另一种方式: 注意:lineinfile模块只适用于修改少量环境变 ...

  2. logback日志文件的使用

    1.引入Jar包,Maven pom.xml <!-- Logging with SLF4J & LogBack --> <dependency> <groupI ...

  3. nodejs . module.exports

    //utils.js let a = 100; console.log(module.exports); //能打印出结果为:{} console.log(exports); //能打印出结果为:{} ...

  4. ASP.NET MVC easyUI-datagrid 分页

    本文写的是最简单的 按照API文档来写的分页.就是插件自带的分页效果. 一.html代码:field就是代表你后台数据的对应的列名. <table id="dg" class ...

  5. 数据库MySQL--数据操作语言DML(插入、修改、删除)

    例子文件:https://files-cdn.cnblogs.com/files/Vera-y/girls.zip 一.插入 方式一: 语法: insert into 表名(列名,.....) val ...

  6. css---8 过渡属性刨析

    1.       transition-property 默认值为 all,表示所有可被动画的属性都表现出过渡动 可以指定多个 property 属性值: none 没有过渡动画. all 所有可被动 ...

  7. Java集合框架(List,Set,Map)

    单列集合基本框架 List接口特点:1. 它是一个元素存取有序的集合.例如,存元素的顺序是11.22.33.那么集合中,元素的存储就是按照11.22.33的顺序完成的). 2. 它是一个带有索引的集合 ...

  8. day30 python类的继承,抽象类等

    Python之路,Day17 = Python基础17-面向对象入门 继承 class Student(People): pass print(Student.__bases__) # 查看 Stud ...

  9. VS2010-MFC(菜单:VS2010菜单资源详解)

    转自:http://www.jizhuomi.com/software/210.html 上一节讲了标签控件Tab Control以后,常用控件的内容就全部讲完了,当然并没有包括所有控件,主要是一些很 ...

  10. 有关Tensorboard问题

    先说我的各个版本: 操作系统: win7 64 Python: 3.5 Tensorflow: 1.2 Tensorboard: 1.6 错误一: 只显示Graphs,不显示Histogram和Sca ...