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 1Sample Output 1:
Yes 2 1 6 4 7 3 5Sample Input 2:
4 1 2 3 4 2 4 3 1Sample Output 2:
No 2 1 3 4
题目大意:给出一个二叉树的前序序列和后序序列,如果中序序列唯一则输出Yes,否则输出No,并输出任意一个中序序列即可
思路:构建函数getin,函数接收四个参数,前序序列的开始结束位置和后序序列的起始结束位置。每次先保存当前子树的根,递归求左子树后把根push进vector,然后调用右子树。前序序列去掉第一个元素(即根)后,后序序列去掉最后一个元素后,就是左右子树合在一起的序列,下一步是把左右子树分开。当前 前序序列的第二个元素即是左子树的根,在后序序列中寻找相同元素,记下位置i;同理根据当前后序序列的倒数第二个元素,在前序序列中寻找相同的元素,位置记为j。此时i为后序序列中左子树根节点的位置,j为前序序列中右子树根节点的位置(如果是只有单个子树的情况,i指向了右子树根节点,j指向了左子树的根节点,即i和j的位置发生了互换,需要判断此情况,即出现了不确定的中序序列,需要记一下yes no,此时左右子树只调用一个即可)。递归调用左右子树。注意返回条件,函数一开始判断开始位置在结束位置之后时直接return,相等时说明当前是叶子节点,push入vector之后return即可。
#include<cstdio>
#include<vector>
using namespace std;
int n,preo[30],poso[30];
bool yn=true;
vector<int>ans;
void getin(int s,int e,int sp,int ep){
if(s>e)return;
int rot=preo[s];
if(s==e){
ans.push_back(rot);return;
}
int i=sp,j=s;
while(preo[s+1]!=poso[i])i++;
while(preo[j]!=poso[ep-1])j++;
if(i==ep-1||j==s+1){
yn=false;
ans.push_back(rot);
getin(s+1,e,sp,ep-1);
}
else{
getin(s+1,j-1,sp,i);
ans.push_back(rot);
getin(j,e,i+1,ep-1);
}
}
int main(){
scanf("%d",&n);
int i;
for(i=0;i<n;i++){
scanf("%d",&preo[i]);
}
for(i=0;i<n;i++){
scanf("%d",&poso[i]);
}
getin(0,n-1,0,n-1);
printf("%s\n",yn?"Yes":"No");
for(i=0;i<n;i++){
printf("%d%c",ans[i],i!=n-1?' ':'\n');
}
return 0;
}