团体天梯赛-L2-004 这是二叉搜索树吗?
题目链接:这是二叉搜索树吗?
主要考察BST树(指针建树)和前序遍历
#include<bits/stdc++.h>
using namespace std;
int n,m,cnt;
vector<int> vi,ans;
struct node{
int data;
node *lchild;
node *rchild;
};
void build_bst(node *&root,int data){
if(root==NULL){
root = new node;
root->data = data;
root->lchild = root->rchild = NULL;
return ;
}
if(data<root->data) build_bst(root->lchild,data);
else build_bst(root->rchild,data);
}
void pre_order(node *root){
if(root==NULL) return ;
ans.push_back(root->data);
pre_order(root->lchild);
pre_order(root->rchild);
}
void post_order(node *root){
if(root==NULL) return ;
post_order(root->lchild);
post_order(root->rchild);
cnt++;
if(cnt==1) cout<<root->data;
else cout<<" "<<root->data;
}
void mirror(node *root){
if(root==NULL) return ;
swap(root->lchild,root->rchild);
mirror(root->lchild);
mirror(root->rchild);
}
int main(){
cin>>n;
node *root = NULL;
for(int i=0;i<n;i++){
cin>>m;
build_bst(root,m);
vi.push_back(m);
}
pre_order(root);
if(ans==vi){
cout<<"YES"<<endl;
post_order(root);
return 0;
}
else{
ans.clear();
cnt = 0;
mirror(root);
pre_order(root);
if(vi==ans){
cout<<"YES"<<endl;
post_order(root);
}
else{
cout<<"NO";
}
}
return 0;
}