#include<bits/stdc++.h>
using namespace std;
int preorder[1000],postorder[1000];
int flag = 1;
int less1 = 0;
bool isjudge(int prel , int length , int index){
if(less1 == 1){
for(int i = prel+1 ; i < index ; i++){
if(preorder[i] < preorder[prel])
return false;
}
for(int i = index ; i< prel+length ; i++){
if(preorder[i] > preorder[prel])
return false;
}
}else{
for(int i = prel+1 ; i < index ; i++){
if(preorder[i] > preorder[prel])
return false;
}
for(int i = index ; i< prel+length ; i++){
if(preorder[i] < preorder[prel])
return false;
}
}
return true;
}
void generate(int prel ,int postl ,int length){
if(length <= 0)
return;
if(length==1){
postorder[postl+length-1] = preorder[prel];
return;
}
postorder[postl+length-1] = preorder[prel];
int index = -1;
if(less1 == 1){
for(int i = prel ; i < prel+length ;i++){
if(preorder[i]<preorder[prel]){
index = i;
break;
}
}
if(index == -1)
index = prel+length;
if(isjudge(prel,length,index)){
generate(prel+1,postl,index-prel-1);
generate(index,postl+index-prel-1,length-index+prel);
}else{
flag = -1;
return;
}
}else{
for(int i = prel ; i < prel+length ;i++){
if(preorder[i]>preorder[prel]){
index = i;
break;
}
}
if(index == -1)
index = prel+length;
if(isjudge(prel,length,index)){
generate(prel+1,postl,index-prel-1);
generate(index,postl+index-prel-1,length-index+prel);
}else{
flag = -1;
return;
}
}
}
int main(){
int n;
cin>>n;
for(int i = 0 ; i < n ; i++)
cin>>preorder[i];
if(preorder[0] > preorder[1])
less1 = -1;
else
less1 = 1;
generate(0,0,n);
if(flag == -1)
cout<<"NO";
else{
cout<<"YES"<<endl;
for(int i = 0 ; i < n ; i++){
if(i == 0)
cout<<postorder[i];
else
cout<<" "<<postorder[i];
}
}
}
Is It a Binary Search Tree采用序列下标的生成方法
最新推荐文章于 2024-11-09 20:38:27 发布