✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1127 ZigZagging on a Tree (pintia.cn)
🔑中文翻译:Z 字形遍历二叉树
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1127 ZigZagging on a Tree
Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in “zigzagging order” – that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
8 12 11 20 17 1 15 8 5 12 20 17 11 15 8 5 1
Sample Output:
1 11 5 8 17 12 20 15
题意
给定中序和后序遍历结果,确定一颗二叉树。
要求输出该二叉树 Z
字形遍历的结果,Z
字形遍历规则如下:
类似于层次遍历,第一层从右往左遍历,第二层从左往右遍历,第三层再从右往左遍历,以此类推。。。
思路
-
由于题目给定每个结点的值都不同,所以可以用哈希表存储每个结点在中序数组中的下标,方便后续使用。
-
通过下标构建二叉树(其中
k-1-il
表示左子树结点个数): -
通过
bfs
进行Z
字形层次遍历,并输出最终结果。这里有个技巧就是在原有的层次遍历过程中加一个附加条件step
,只要step
等于奇数,就将当层的遍历结果进行反转,然后加入到答案中。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 40;
int n;
int in[N], post[N];
unordered_map<int, int> l, r, pos;
int q[N];
int build(int il, int ir, int pl, int pr)
{
int root = post[pr]; //获得根结点
int k = pos[root]; //获得根结点在中序数组中的下标
if (il < k) l[root] = build(il, k - 1, pl, pl + k - il - 1);
if (ir > k) r[root] = build(k + 1, ir, pl + k - il - 1 + 1, pr - 1);
return root;
}
void bfs(int root)
{
int hh = 0, tt = 0;
q[0] = root;
int step = 0;
while (hh <= tt)
{
int head = hh, tail = tt;
while (hh <= tail)
{
int t = q[hh++];
if (l.count(t)) q[++tt] = l[t];
if (r.count(t)) q[++tt] = r[t];
}
if (++step % 2) reverse(q + head, q + tail + 1); //Z字形遍历
}
}
int main()
{
cin >> n;
//输入中序数组,并记录每个元素在中序数组中的下标位置
for (int i = 0; i < n; i++)
{
cin >> in[i];
pos[in[i]] = i;
}
//输入后序数组
for (int i = 0; i < n; i++) cin >> post[i];
int root = build(0, n - 1, 0, n - 1);
bfs(root);
cout << q[0];
for (int i = 1; i < n; i++) cout << " " << q[i];
cout << endl;
return 0;
}