题目描述

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. Windows XP浏览器支持度

    XP最多支持到IE8 谷歌已经结束对Windows XP版Chrome浏览器的支持. 2015年11月,谷歌表示会在2015年结束后,结束对Windows XP版Chrome浏览器的支持.而今,随着2 ...

  2. JS对象 字符串分割 split() 方法将字符串分割为字符串数组,并返回此数组。 语法: stringObject.split(separator,limit)

    字符串分割split() 知识讲解: split() 方法将字符串分割为字符串数组,并返回此数组. 语法: stringObject.split(separator,limit) 参数说明: 注意:如 ...

  3. C# async await 举个栗子

    首先,async 和 await 代表异步执行和等待. async是一个标记,告诉编译器,我可能是一个异步方法. await 代表等待,告诉编译器,这里等我返回结果. 下面,我们简单说一下. 一 , ...

  4. [JZOJ3347] 【NOI2013模拟】树的难题

    题目 题目大意 给你一棵树,每个节点有三种黑.白.灰三种颜色. 你要割掉一些边(每条边被割需要付出一定的代价),使得森林的每棵树满足: 没有黑点或至多一个白点. 思考历程 这题一看就知道是一个树形DP ...

  5. duilib库分析2.第一篇UIManager

    DUiLib 源码分析 ——以UiLib 1.01版为分析目标--------------------------------------------------------------------- ...

  6. (1)mysql数据库操作

    1.安装mysql https://dev.mysql.com/downloads/windows/installer/8.0.html 2.mysql启停 运行mysql         net s ...

  7. Windows平台编译libevent

    使用VisualStudio来编译,我的电脑上安装的是VS2013.1.在开始菜单项里面(或者在VS安装路径中)打开Developer Command Prompt for VS2013.exe2.在 ...

  8. day23_1-re模块之转义字符、分组、方法

    #!/usr/bin/env python# -*- coding:utf-8 -*-# ------------------------------------------------------- ...

  9. day 68 Django基础四之模板系统

      Django基础四之模板系统   本节目录 一 语法 二 变量 三 过滤器 四 标签Tags 五 模板继承 六 组件 七 自定义标签和过滤器 八 静态文件相关 一 语法   模板渲染的官方文档 关 ...

  10. namespace 命名空间

    namespace作用:资源隔离 当我们不指定namespace时,默认放在default下 创建namespace kubectl create namespace 资源名称 在生产中,我们建议一个 ...