邻接矩阵实现有向图,使用 DFS 思想生成和处理数据
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.
Problem: PAT-A 1127 ZigZagging on a Tree
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
1 | 8 |
Sample Output
1 | 1 11 5 8 17 12 20 15 |
Analysis
通过中序和后序序列构造二叉树,然后按层输出。与普通层次遍历不同的是,偶数层(0 层开始)正序输出,奇数层倒序输出。使用 DFS 或 BFS 遍历整个树,记录各个结点的层号,将数据按层存放于数组。输出时逐层输出,根据层号判断使用正序或倒序输出。
Code
1 |
|
Tsukkomi
巩固了一遍中序 + 后序序列生成二叉树,还行吧。一开始数组开了 35,交上去居然段错误??题目标的 N <= 30,但结点序号范围并不在 [1, N]。