PAT - 团体程序设计天梯赛-练习集 - L2-006 - 树的遍历
2017-03-22 15:42
295 查看
Problem : 树的遍历
Descritption :
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
Solution :
后序遍历的特点就是序列最后一个元素是根,其余的部分连续是左子树和右子树;中序遍历的特点就是序列的中间某个是根,左右分别是其左右子树。我们根据这两个特点,利用后序遍历序列中的根在中序遍历序列中查找,得出其左右子树的规模,用这个规模在后序遍历序列中继续划分递归!利用bfs队列的方式可以得出层序遍历。
Code (C++) :
Descritption :
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
Solution :
后序遍历的特点就是序列最后一个元素是根,其余的部分连续是左子树和右子树;中序遍历的特点就是序列的中间某个是根,左右分别是其左右子树。我们根据这两个特点,利用后序遍历序列中的根在中序遍历序列中查找,得出其左右子树的规模,用这个规模在后序遍历序列中继续划分递归!利用bfs队列的方式可以得出层序遍历。
Code (C++) :
#include <stdio.h> #include <string.h> #define MAX_LINE 35 typedef struct tagNode { int src, des; int s, d; tagNode() {} tagNode(int src, int des, int s, int d) : src(src), des(des), s(s), d(d) {} }Node; int n; int next[MAX_LINE], mid[MAX_LINE]; Node que[MAX_LINE * MAX_LINE]; int head, tail; int find_root(int x, int s, int d) { for (int i = s; i <= d; i++) if (x == mid[i]) return i; return -1; } int main() { //freopen("in", "r", stdin); while (~scanf("%d", &n)) { for (int i = 0; i < n; i++) scanf("%d", &next[i]); for (int i = 0; i < n; i++) scanf("%d", &mid[i]); head = tail = 0; que[tail++] = Node(0, n - 1, 0, n - 1); while (tail != head) { Node pre = que[head++]; int root_pos = find_root(next[pre.des], pre.s, pre.d); int m = pre.d - root_pos; m = pre.des - 1 - m; if (pre.src <= m) que[tail++] = Node(pre.src, m, pre.s, root_pos - 1); if (m + 1 <= pre.des - 1) que[tail++] = Node(m + 1, pre.des - 1, root_pos + 1, pre.d); } for (int i = 0; i < tail; i++) printf("%d%c", next[que[i].des], i == tail - 1 ? '\n' : ' '); } return 0; }
相关文章推荐
- PAT 团体程序设计天梯赛-练习集 L2-006. 树的遍历
- PAT 团体程序设计天梯赛-练习集 L2-006. 树的遍历【数据结构】
- 团体程序设计天梯赛-练习集L2-006. 树的遍历
- 团体程序设计天梯赛-练习集 L2-006. 树的遍历 解题报告
- 团体程序设计天梯赛-练习集 L2-006 树的遍历 根据后序中序建树+BFS
- L2-006. 树的遍历-PAT团体程序设计天梯赛GPLT
- 团体程序设计天梯赛-练习集 L2-006. 树的遍历
- 团体程序设计天梯赛-练习集L2-006. 树的遍历
- PAT - 团体程序设计天梯赛-练习集 - L2-004 - 这是二叉搜索树吗?
- PAT - 团体程序设计天梯赛-练习集 - L2-014 - 列车调度
- PAT 团体程序设计天梯赛-练习集 L2-003. 月饼
- PAT 团体程序设计天梯赛-练习集 L2-009. 抢红包
- PAT-团体程序设计天梯赛-练习集-L1-006. 连续因子
- PAT-团体程序设计天梯赛-练习集-L2-003. 月饼
- 团体程序设计天梯赛L2-006 树的遍历
- 团体程序设计天梯赛L2-006 树的遍历(数据结构)
- 团体程序设计天梯赛-练习集 PAT L2-001 紧急救援
- PAT 团体程序设计天梯赛-练习集 L2-001. 紧急救援 【dijkstra】
- pat 团体天梯赛 L2-006. 树的遍历
- PAT 团体程序设计天梯赛-练习集 题解(凑零钱,堆栈,社交集群)