题目大意
根据一个二叉树的前序和后序遍历序列,判断此二叉树是否唯一,并输出此二叉树的中序遍历序列,若不唯一则随意输出一个满足前序与后序遍历序列的中序序列。
思路
二叉树不唯一的情况是当前序和后序遍历只包含两个元素时,此时无法确定叶子结点属于右子树还是左子树,只要在转中序序列的递归函数中判断当前递归层中序列中元素的个数是否为两个即可。
原题
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
AC代码(C++)
#include <iostream>
#include <vector>
using namespace std;
int N, pre[35], post[35], judge = 1;
vector<int>res;
void transform_(int pl, int pr, int pol, int por){
if(por > pol){
if(por == pol + 1)judge = 0;
int root = post[por - 1], pos = pl;
for(int i = pl; i <= pr; i++){
if(pre[i] == root){
pos = i;
break;
}
}
transform_(pl + 1, pos - 1, pol, por + pos - pr - 2);
res.push_back(post[por]);
transform_(pos, pr, por + pos - pr - 1, por - 1);
}else if(pol == por) res.push_back(post[por]);
else return;
}
int main(){
scanf("%d", &N);
for(int i = 0; i < N; i++)scanf("%d", &pre[i]);
for(int i = 0; i < N; i++)scanf("%d", &post[i]);
transform_(0, N - 1, 0, N - 1);
printf("%s\n", judge ? "Yes" : "No");
for(int i = 0; i < N; i++){
if(i == 0)printf("%d", res[i]);
else printf(" %d", res[i]);
}printf("\n");
return 0;
}