1043 Is It a Binary Search Tree (25 分)。查找树的建立➕插入➕前后序遍历,都是模板一样的组合
作者:互联网
#include<iostream>
#include<vector>
using namespace std;
struct node{
int data;
node *left,*right;
};
void insert(node* &root,int data){
if(root==NULL){
root=new node;
root->data=data;
root->left=root->right=NULL;
return;
}
if(data<root->data)
insert(root->left,data);
else insert(root->right,data);
}
void preorder(node* root,vector<int> &vi){
if(root==NULL) return;
vi.push_back(root->data);
preorder(root->left,vi);
preorder(root->right,vi);
}
void preordermirror(node* root,vector<int> &vi){
if(root==NULL) return;
vi.push_back(root->data);
preordermirror(root->right,vi);
preordermirror(root->left,vi);
}
void postorder(node* root,vector<int> &vi){
if(root==NULL) return;
postorder(root->left,vi);
postorder(root->right,vi);
vi.push_back(root->data);
}
void postordermirror(node* root,vector<int> &vi){
if(root==NULL) return;
postordermirror(root->right,vi);
postordermirror(root->left,vi);
vi.push_back(root->data);
}
vector<int> origine,pre,prem,post,postm;
int main(){
int n,data;
node* root=NULL;
cin>>n;
for(int i=0;i<n;i++){
cin>>data;
origine.push_back(data);
insert(root,data);
}
preorder(root,pre);
preordermirror(root,prem);
postorder(root,post);
postordermirror(root,postm);
if(origine==pre){
if(origine==pre){
cout<<"YES"<<endl;
for(int i=0;i<post.size();i++){
cout<<post[i];
if(i!=post.size()-1) cout<<" ";
}
}
}
else if(origine==prem){
cout<<"YES"<<endl;
for(int i=0;i<postm.size();i++){
cout<<postm[i];
if(i<postm.size()-1) cout<<" ";
}
}
else cout<<"NO"<<endl;
return 0;
}
标签:1043,Binary,Search,right,node,data,vi,NULL,root 来源: https://blog.csdn.net/qq_42835526/article/details/113738504