Ladder Tournament L2-004
-
A binary search tree can be recursively defined as a binary tree with the following properties: For any node,
The key value of all nodes in the left subtree is less than the key value of the node; the key value
of all nodes in the right subtree is greater than or equal to the key value of the node;
the left and right subtrees are binary search trees.
The so-called "mirror" of the binary search tree is the tree obtained by swapping the positions of the left and right subtrees of all nodes.Given a sequence of integer key values, please write a program to determine whether this is the result of pre-traversing a binary search tree or its mirror image.
Input format:
The first line of input gives a positive integer N (≤1000). The next line gives N integer key values, separated by spaces.Output format:
If the input sequence is the result of preorder traversal of a binary search tree or its mirror, first output YES in one line, and then output the result of subsequent traversal of the tree in the next line. There is 1 space between the numbers, and no extra spaces are allowed at the beginning and end of a line. If the answer is no, output NO.
Binary search tree, preorder traverses the first number as the root, searches from left to right for the last node with a value smaller than the root, denoted as i; searches for the first node with a value larger than the root from right to left, Denoted as j, it is a binary search tree if and only if ji=1
#include<bits/stdc++.h>
using namespace std;
int n,sum=0,a[1005],tr[1005],sl[1005],sr[1005];
bool vis=0;
bool build1(int l,int r){
tr[++sum]=a[l];
if(l==r) return 1;
int x=l,y=r+1,k=sum;
while(x+1<=n&&a[l]>a[x+1]) x++;
while(y-1>l&&a[y-1]>=a[l]) y--;
if(x!=y-1) return 0;
if(x>l){
sl[k]=l+1;
if(!build1(l+1,x)) return 0;
}
if(y<=r){
sr[k]=y;
if(!build1(y,r)) return 0;
}
return 1;
}
bool build2(int l,int r){
tr[++sum]=a[l];
if(l==r) return 1;
int x=l,y=r+1,k=sum;
while(x+1<=n&&a[l]<=a[x+1]) x++;
while(y-1>l&&a[y-1]<a[l]) y--;
if(x!=y-1) return 0;
if(x>l){
sl[k]=l+1;
if(!build2(l+1,x)) return 0;
}
if(y<=r){
sr[k]=y;
if(!build2(y,r)) return 0;
}
return 1;
}
void print(int fa){
if(!fa) return;
print(sl[fa]);
print(sr[fa]);
if(vis) cout<<" ";
else vis=1;
cout<<tr[fa];
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
if(build1(1,n)){
cout<<"YES"<<endl;
print(1);
return 0;
}
sum=0;
memset(tr,0,sizeof(tr));
memset(sl,0,sizeof(sl));
memset(sr,0,sizeof(sr));
if(build2(1,n)){
cout<<"YES"<<endl;
print(1);
return 0;
}
cout<<"NO";
return 0;
}