ural 1136. Parliament 中后序建树
2015-08-20 13:56
316 查看
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1136
题目描述:应用环境就不看了,摘要出来就是,给定后序序列,中序就是递增序,建树后按照它的遍历规则求新序列(先右后左再中间);
思路感觉还是蛮清晰的,后序序列从后往前插入二叉树,就可以还原了,受到启发其它的中序只要能够定义偏序比较就可以用类似的方法轻松建树!
上AC代码:
题目描述:应用环境就不看了,摘要出来就是,给定后序序列,中序就是递增序,建树后按照它的遍历规则求新序列(先右后左再中间);
思路感觉还是蛮清晰的,后序序列从后往前插入二叉树,就可以还原了,受到启发其它的中序只要能够定义偏序比较就可以用类似的方法轻松建树!
上AC代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdio.h> #include <string> #include <vector> #include <queue> #include <cmath> #include <map> using namespace std; struct Node{ Node *left, *right; int id; Node(int num) :id(num), left(nullptr), right(nullptr){} void uniqTraversal(){ if (this->right != nullptr) this->right->uniqTraversal(); if (this->left != nullptr) this->left->uniqTraversal(); cout << this->id << endl; } }; void insertTree(Node* &ptr, int num){ if (ptr == nullptr) ptr = new Node(num); else if (num < ptr->id) insertTree(ptr->left, num); else insertTree(ptr->right, num); } void func(){ int n, num, i; Node* head = nullptr; cin >> n; vector<int>v; for (i = 0; i < n; i++){ cin >> num; v.push_back(num); } for (i = v.size() - 1; i >= 0; i--) insertTree(head, v[i]); head->uniqTraversal(); } int main(){ freopen("out.txt", "w", stdout); freopen("in.txt", "r", stdin); func(); }
相关文章推荐
- Linux命令(三)
- nginx location及rewrite的写法说明
- hdu 5317 RGCDQ 2015 Multi-University Training Contest 3
- 使用ngx_slowfs_cache模块构建本地缓存
- RGB、YUV和YCbCr
- Item 3:尽量使用常量 Effective C++笔记
- Item 2:避免使用define Effective C++笔记
- 【Android 应用开发】Android资源文件 - 使用资源存储字符串 颜色 尺寸 整型 布尔值 数组
- jQuery超赞的评分插件(8款)
- Java 异常处理的误区和经验总结
- 白话空间统计之十:标准距离
- 菜鸟系列——约瑟夫环
- Marvell发布4核A53芯片 基带支持Cat.7 LTE---ESM
- Item 1:将C++视作一系列的语言 Effective C++笔记
- 百度云加速疑似进行了DNS劫持
- 让你的网站飞起来
- 使用maven 时 com.sun.image.codec.jpeg 找不到类
- java中的反射机制
- Android性能优化(二),Layout布局优化
- C# log4net 不输出日志