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.
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.
For each test case, first printf in a line
Yes
if the tree is unique, orNo
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.
7 1 2 3 4 6 7 5 2 6 7 4 5 3 1
Yes 2 1 6 4 7 3 5
4 1 2 3 4 2 4 3 1
No 2 1 3 4
1 /* 2 Data: 2019-06-10 20:49:53 3 Problem: PAT_A1119 Pre- and Post-order Traversals 4 AC: 36:40 5 6 题目大意: 7 给出先序和后序遍历,输出任意中序遍历,并判断是否唯一 8 */ 9 10 #include<cstdio> 11 #include<vector> 12 using namespace std; 13 const int M=110; 14 int pre[M],post[M],ans=1; 15 vector<int> in; 16 17 void Create(int preL, int preR, int postL, int postR) 18 { 19 //根结点:pre[preL] == post[postR] 20 //左子树的根结点:pre[preL+1] 21 //右子树的根结点:post[postR-1] 22 23 //空子树 24 if(preL > preR) 25 return; 26 //叶子结点 27 if(preL == preR) 28 { 29 in.push_back(pre[preL]); 30 return; 31 } 32 //分支结点 33 int k; 34 ///确定右子树根结点,在先序序列中的位置 35 for(k=preL+1; k<=preR; k++) 36 if(pre[k] == post[postR-1]) 37 break; 38 //左子树的规模 39 int numLeft = k-preL-1; 40 //当左子树的规模为0时, 41 //意味着右子树既可以是左子树,也可以是右子树, 42 //此时该二叉树不唯一,默认右子树 43 if(numLeft==0) 44 ans=0; 45 Create(preL+1,preL+numLeft,postL,postL+numLeft-1); 46 in.push_back(pre[preL]); 47 Create(preL+numLeft+1,preR,postL+numLeft,postR-1); 48 49 } 50 51 int main() 52 { 53 #ifdef ONLINE_JUDGE 54 #else 55 freopen("Test.txt", "r", stdin); 56 #endif 57 58 int n; 59 scanf("%d", &n); 60 for(int i=0; i<n; i++) 61 scanf("%d", &pre[i]); 62 for(int i=0; i<n; i++) 63 scanf("%d", &post[i]); 64 Create(0,n-1,0,n-1); 65 66 if(ans) printf("Yes\n"); 67 else printf("No\n"); 68 for(int i=0; i<in.size(); i++) 69 printf("%d%c", in[i], i==in.size()-1?‘\n‘:‘ ‘); 70 71 return 0; 72 }
PAT_A1119 Pre- and Post-order Traversals
原文:https://www.cnblogs.com/blue-lin/p/11000527.html