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:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
Sample Output 1:
Yes
2 1 6 4 7 3 5
Sample Input 2:
4
1 2 3 4
2 4 3 1
Sample Output 2:
No
2 1 3 4
题目大意:
给出n个结点的前序与后序,要求输出其中序,如果不唯一则输出No,否则输出Yes。
思路:
唯一能确定的是根,一定要明确当前序的左子树的根等于后序后子树的根的时候其实是无法唯一确定一棵树的(因为前序满足根左右,后序满足左右根,当出现了根左等于右根的情况,我们不知道该信前序还是后序,无法识别出是左子树还是右子树)。因为只要随意一种中序即可,那么不妨都假设成pre的根后面一个提供左子树,post的根前面一个提供右子树,如果左右子树相等那么就没有右子树。只要inorder一次,录入的即是中序遍历。
我们先假设就是唯一的,当出现上述情况,左子树根==右子树根,那么就要判定为不唯一咯。
参考代码:
#include<cstdio>
#include<vector>
using namespace std;
vector<int> pre, post, in;
int n;
int cnt;
bool unique =true;
void getin(int prst, int pred, int ptst, int pted){
if(prst == pred){
in.push_back(pre[prst]);
return;
}
if(pre[prst] == post[pted]){
int l = pted - 1;
while(l > ptst && pre[prst + 1] != post[l]) l--;
getin(prst + 1, prst + l - ptst +1, ptst, l);
in.push_back(pre[prst]);
if(pted - 1 - l >= 1) getin(prst + l - ptst + 2, pred, l + 1, pted - 1);
else unique = false;
}
}
int main(){
scanf("%d", &n);
pre.resize(n), post.resize(n);
for(int i = 0; i < n; ++i) scanf("%d", &pre[i]);
for(int i = 0; i < n; ++i) scanf("%d", &post[i]);
getin( 0, n - 1, 0, n - 1);
printf("%s\n", unique == true? "Yes": "No");
for(int i = 0; i < n; ++i)
printf("%d%c", in[i], i != n - 1? ' ': '\n');
return 0;
}