PAT a1127题解
来源:互联网 发布:永宏编程手册 编辑:程序博客网 时间:2024/06/14 06:57
#include<cstdio> #include<vector> #include<queue> using namespace std; const int maxn = 35; int in[maxn], post[maxn]; struct Node { int data; int depth; Node*l, *r; Node():l(NULL),r(NULL){} }; int N, maxdepth = -1; Node*create(int i1, int i2, int p1, int p2) { if (i1 > i2 || p1 > p2)return NULL; Node*root = new Node(); root->data = post[p2]; int k; for (int i = i1; i <= i2; i++) { if (in[i] == root->data) { k = i; break; } } root->l = create(i1, k - 1, p1, p1 + k - 1 - i1); root->r = create(k+1, i2, p2-1-(i2-k-1), p2-1); return root; } vector<int> nodes[maxn]; void BFS(Node*root) { queue<Node*>Q; root->depth = 0; Q.push(root); while (!Q.empty()) { Node*f = Q.front(); Q.pop(); maxdepth = max(maxdepth, f->depth); nodes[f->depth].push_back(f->data); if (f->l) { f->l->depth = f->depth + 1; Q.push(f->l); } if (f->r) { f->r->depth = f->depth + 1; Q.push(f->r); } } } int main() { scanf("%d", &N); for (int i = 0; i < N; i++) scanf("%d", &in[i]); for (int i = 0; i < N; i++) scanf("%d", &post[i]); Node*root = NULL; bool first = true; root = create(0, N - 1, 0, N - 1); BFS(root); for (int i = 0; i <= maxdepth; i++) { if (i % 2 == 0) { for (int j = 0; j < nodes[i].size(); j++) { if (first) { first = false; printf("%d", nodes[i][nodes[i].size() - 1 - j]); } else printf(" %d", nodes[i][nodes[i].size() - 1 - j]); } } else { for (int j = 0; j < nodes[i].size(); j++) { if (first) { first = false; printf("%d", nodes[i][j]); } else printf(" %d", nodes[i][j]); } } } return 0; }
阅读全文
1 0
- PAT a1127题解
- PAT-A1127
- PAT A1127
- PAT A1127. ZigZagging on a Tree (30)
- PAT A1127 ZigZagging on a Tree
- PAT-A1127. 二叉树-中序后序建树,Z字遍历
- PAT 1001-1010 题解
- PAT 1011-1020 题解
- PAT 1021-1030 题解
- PAT 1031-1040 题解
- PAT 1041-1050 题解
- PAT 1051-1060 题解
- PAT(basic level)题解
- PAT乙级题解
- PAT题解目录
- PAT甲级题解目录
- PAT乙级题解目录
- PAT甲级1001题解
- 初识Hdoop
- 使用Java实现多线程下载断点续传功能案例
- PAT a1126题解
- python : trans position cipher
- python3编码转换
- PAT a1127题解
- unity3D学习之声音的采集与处理-audio菜鸟笔记1
- PoEdu_Python_Lesson009_类的基础用法、使用dump写数据到json文件的注意点
- 1065. A+B and C (64bit) (20)
- SVM(Support Vector Machine)分类器详解
- 安卓上裁剪m4a | 铃声是怎么制作出来的
- 1006换个格式输出整数 (15)
- pythonWeb -- Django开发- 模型Model 和 数据库的操作
- 203. Remove Linked List Elements(Java)