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
题意 给出二叉树的前序和后序,我们都知道通过前序和后序有时候是不能确定一个二叉树的。这个题就是让我们判断给出的前序和中序能不能唯一的确定一个二叉树,并输出一个可能的中序 怎么判断二叉树唯不唯一就是看除了叶子节点的节点的儿子有几个,如果有两个就没问题,如果有一个我们就无法确定他是左孩子还是右孩子,此时就无法确定
#include<bits/stdc++.h> using namespace std; int n; int pre[35],post[35]; bool isUnique = true; vector<int>inorder; void buildTree(int preL,int preR,int postL,int postR) { if(preL==preR) { inorder.push_back(pre[preL]); return; } if(pre[preL]==post[postR]) { int i=preL+1; while(i<=preR&&pre[i]!=post[postR-1]) i++; if(i-preL>1) buildTree(preL+1,i-1,postL,postL+(i-preL-1)-1); else//如果有一个节点 就不能确定在左还是右 isUnique=false; inorder.push_back(post[postR]); buildTree(i,preR,postL+(i-preL-1),postR-1); } } 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]); buildTree(0,n-1,0,n-1); if(isUnique) printf("Yes\n"); else printf("No\n"); for(int i=0;i<inorder.size();i++) { if(!i) cout << inorder[i]; else cout << " " << inorder[i]; } cout<< endl; }