搜索树
struct tnode{
element data;
struct tnode *left;
struct tnode *right;
};
typedef struct tnode *bintree;
typedef struct tnode *position;
bintree bst;
//递归
position find(element x,bintree bst){
if(!bst){
return NULL;
}
if(x<bst->data){
return find(x,bst->left);
}else if(x>bst->data){
return find(x,bst->right);
}else{
return bst;
}
}
//迭代
position find(element x,bintree bst){
while(bst){
if(x>bst->data){
bst=bst->right;
}else if(x<bst->data){
bst=bst->left;
}else{
break;
}
}
return bst;
}
//迭代
position findmax(bintree bst){
if(bst){
while(bst->right){
bst=bst->right;
}
}
return bst;
}
//递归
position findmin(bintree bst){
if(!bst) return bst;
else if(!bst->left) return bst;
else return find(bst->left);
}
//插入
bintree insert(element x,bintree bst){
if(!bst){
bst=malloc(sizeof(struct tnode));
bst->data=x;
bst->left=bst->right=NULL;
}
while(bst){
if(x>bst->data){
bst->right=insert(x,bst->right);
}else if(x<bst->data){
bst->left=insert(x,bst->left);
}else
}
return bst;
}
//删除
bintree deleteq(bintree bst,element x){
position temp;
if(!bst){
printf("not find");
}else{
if(x>bst->data){
bst->right=deleteq(bst->right,x);
}else if(x<bst->data){
bst->left=deleteq(bst->left,x);
}else{
if(bst->left&&bst->right){
temp=findmax(x,bst->left);
bst->data=temp->data;
bst->left=deleteq(bst->left,temp->data);
}else{
temp=bst;
if(!bst->left){
bst=bst->right;
}else{
bst=bst->left;
}
free(temp);
}
}
return bst;
}
bintree deleteq(element x,bintree bst){
position=temp;
if(!bst){
printf("not find");
}
else{
if(x>bst->data){
bst->right=deleteq(x,bst->right);
}else if(x<bst->data){
bst->left=deleteq(x,bst->left);
}else{
if(bst->left&&bst->right){
temp=findmin(bst->right);
bst->data=temp->data;
bst->right=deleteq(x,bst->data);
}else{
temp=bst;
if(!bst->left){
bst=bst->right;
}else{
bst=bst->left;
}
free(temp);
}
}
}
return bst;
}