代码如下
#include<iostream>
using namespace std;
struct node{
int val;
node *l,*r;
node(int val = 0, node *l = NULL, node *r = NULL) :val(val), l(l), r(r) {}
};
void create(node *&root,int x){
if(root == NULL) root = new node(x);
else{
if(root->val >= x) create(root->l,x);
if(root->val < x) create(root->r,x);
}
}
void preT(node* root){
if(root == NULL) return ;
cout<<root->val<<" ";
preT(root->l);
preT(root->r);
}
void inT(node* root){
if(root == NULL) return ;
preT(root->l);
cout<<root->val<<" ";
preT(root->r);
}
void postT(node* root){
if(root == NULL) return ;
preT(root->l);
preT(root->r);
cout<<root->val<<" ";
}
int main(){
int n,root_val,x;
cout<<"请输入根结点值:";
cin>>root_val;
node* root = new node();
root->val = root_val;
cout<<"请输入该二叉搜索树的结点数(除根结点外):";
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
create(root,x);
}
cout<<"前序遍历如下:"<<endl;
preT(root);
cout<<endl;
cout<<"中序遍历如下:"<<endl;
inT(root);
cout<<endl;
cout<<"后序遍历如下:"<<endl;
postT(root);
return 0;
}