二叉查找树的简单实现
笔记(2018-11-25)
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct node{
int value;
node *left,*right;
node(const int &x,node *lt=NULL,node *rg=NULL)
:value(x),left(lt),right(rg){}
};
node *root=NULL;
void insert(const int &x,node *&t){
if(t==NULL) {t=new node(x);return;}
if(x<t->value) insert(x,t->left);
else insert(x,t->right);
}
void remove(const int &x,node *&t){
if(t==NULL) return;
if(x<t->value) remove(x,t->left);
else if(x>t->value) remove(x,t->right);
else if(t->left!=NULL&&t->right!=NULL){
node *tmp=t->right;
while(tmp->left!=NULL)tmp=tmp->left;
t->value=tmp->value;
remove(tmp->value,t->right);
}
else{
node *oldtmp=t;
t=(t->left!=NULL)?t->left:t->right;
delete oldtmp;
}
}
node *find(const int &x,node *t){
if(t==NULL) return t;
if(t->value==x) return t;
else if(t->value>x) return find(x,t->left);
else return find(x,t->right);
}
void preOrder(node *t){
if(t==NULL) return;
preOrder(t->left);
cout<<t->value<<" ";
preOrder(t->right);
}
void makeEmpty(node *&t){
if(t==NULL) return;
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
int main(){
int num;
srand(time(NULL));
for(int k=0;k<8;++k){
num=rand()%10;
insert(num,root);
}
preOrder(root);
cout<<endl;
node *tmp=find(4,root);
if(tmp!=NULL){
cout<<tmp->value<<endl;
remove(4,root);
}
else cout<<endl;
preOrder(root);
return 0;
}