题目描述

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. Neo4j中實現自定義中文全文索引

    資料庫檢索效率時,一般首要優化途徑是從索引入手,然後根據需求再考慮更復雜的負載均衡.讀寫分離和分散式水平/垂直分庫/表等手段:索引通過資訊冗餘來提高檢索效率,其以空間換時間並會降低資料寫入的效率,因此 ...

  2. c++智能指针(unique_ptr 、shared_ptr、weak_ptr、auto_ptr)

    一.前序 什么是智能指针? ——是一个类,用来存储指针(指向动态分配对象也就是堆中对象的的指针). c++的内存管理是让很多人头疼的事,当我们写一个new语句时,一般就会立即把delete语句直接也写 ...

  3. 百度开平台BAE搭建网站

    百度开平台BAE搭建网站 一.注册:在百度云注册账号,并且登陆 然后实名验证 二.开始搭建 三.部署项目:我们来把我们的项目提交上去 填写百度云的账号密码 四.删除:删除部署项目 以上就是百度开平台B ...

  4. Linux 服务器 个人常用操作命令记录

    1.实时查看log:tail -f 日志文件名 2.查看Apache运行的用户组或用户名:ps aux | grep httpd 或者是: ps -ef | grep httpd 3.查看cronta ...

  5. [笔记]Laravel TDD 胡乱记录

    TDD: 测试驱动开发(Test-Driven Development),TDD的原理是在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码. -- 载自TDD百度百科 参考 ...

  6. thinkphp 模型实例化

    在ThinkPHP中,可以无需进行任何模型定义.只有在需要封装单独的业务逻辑的时候,模型类才是必须被定义的,因此ThinkPHP在模型上有很多的灵活和方便性,让你无需因为表太多而烦恼. 根据不同的模型 ...

  7. SP1296 SUMFOUR - 4 values whose sum is 0

    传送门 解题思路 四个数组一起做有点炸.先把他们合并成两个数组,然后让一个数组有序,枚举另一个数组的元素,二分即可.时间复杂度\(O(n^2logn^2)\) 代码 #include<iostr ...

  8. gulp是什么?

    什么是gulp? gulp初涉 1.什么是gulp? gulp是前端开发过程中一种基于流的代码构建工具,是自动化项目的构建利器:它不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的 ...

  9. eclipse+terminal

    eclipse 怎么安装terminal插件   1 首先打开eclipse,找到help菜单,点击Eclipse Marketplace. 2 在search框里输入Terminal,点击Go查找. ...

  10. jedis3.1.0在weblogic(jdk1.6)中无法运行

    文章目录 错误 探索 总结 错误 在tomcat中运行是没有问题的,可是在weblogic中是不能够运行的,weblogic中的jdk客户要求是1.6的. 如果更换版本jedis2.9.0是没有问题的 ...