1119 Pre- and Post-order Traversals (30 分)
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, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.
Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.
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 preorder 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, first printf in a line Yes
if the tree is unique, or No
if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. 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:
1 | 7 |
Sample Output 1:
1 | Yes |
Sample Input 2:
1 | 4 |
Sample Output 2:
1 | No |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意
给出一棵树的前序及后序遍历,判断二叉树是否唯一,并输出其中序遍历。如果不唯一,输出任一情况。
分析
考虑根结点只有一个孩子的情况,只给出前后序是无法判断该子树是左子树还是右子树的。当出现这种情况时,即为不唯一,又因为输出任一情况即可,为编程方便统一当作右子树处理。
代码
1 |
|