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
#include <cstdio>
#include <cstring>
#include<iostream>
#include <vector>
#include<math.h>
#include<string>
#include <algorithm>
using namespace std;
const int maxn= 1010; //最大顶点数
int pre[maxn],pos[maxn];bool is_unique=1;
const int inf = 0x3fffffff; //无穷大
vector<int> v;
struct node{
int data;
node *lchild,*rchild;
};
node *create(int pre_l,int pre_r,int pos_l,int pos_r){ //下标和值不要搞混
node *root=new node;
if(pre_l>pre_r) return NULL;
root->data=pre[pre_l];
int k,num_left=0;
for(k=pos_l;k<pos_r;k++){ // 已知先后序,如果后序倒数第二个等于先序第二个结点,则不唯一;
num_left++;
if(pos[k]==pre[pre_l+1]) break;
}
if(k==pos_r-1) is_unique=0;
root->lchild=create(pre_l+1,pre_l+num_left,pos_l,k); //most important
root->rchild=create(pre_l+num_left+1 ,pre_r , k+1, pos_r-1);
return root;
}
void in_order(node* root){
if(root){
in_order(root->lchild);
v.push_back(root->data);
in_order(root->rchild);
}
}
int main(){
int n;cin>>n;
for(int i=0;i<n;i++) cin>>pre[i];
for(int i=0;i<n;i++) cin>>pos[i];
node *root =create(0,n-1,0,n-1);
in_order(root);
if(is_unique) cout<<"Yes"<<endl;else cout<<"No"<<endl;
for(int i=0;i<v.size();i++){
if(i!=0) cout<<" ";
cout<<v[i];
}
cout<<endl;
}

浙公网安备 33010602011771号