題目大意
根據(jù)一個(gè)二叉樹的前序和后序遍歷序列励负,判斷此二叉樹是否唯一莺奔,并輸出此二叉樹的中序遍歷序列鸠珠,若不唯一則隨意輸出一個(gè)滿足前序與后序遍歷序列的中序序列饺蔑。
思路
二叉樹不唯一的情況是當(dāng)前序和后序遍歷只包含兩個(gè)元素時(shí)锌介,此時(shí)無法確定葉子結(jié)點(diǎn)屬于右子樹還是左子樹,只要在轉(zhuǎn)中序序列的遞歸函數(shù)中判斷當(dāng)前遞歸層中序列中元素的個(gè)數(shù)是否為兩個(gè)即可猾警。
原題
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;
}