/**
* ---二叉排序树-----
* 建树
* 查找
* 中序遍历
* 删除
*/
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lchild,*rchild;
}BSTNode,*BiTree;
/**
* -----递归------
* @param T
* @param elment
* @return
*/
ElemType InsertSBT(BiTree &T, ElemType elment){
if(NULL==T){
T=(BiTree)malloc(sizeof(BSTNode));
T->data=elment;
T->lchild=T->rchild=NULL;
return 1;
}else if(elment==T->data){
return 0;
}else if(elment>T->data){
return InsertSBT(T->rchild,elment);
}else if(elment<T->data){
return InsertSBT(T->lchild,elment);
}
}
/**
* ----建树----
* @param T
* @param str
* @param len
*/
void CreatBST(BiTree &T,ElemType str[],int len){
int i;
for(i=0;i<len;i++){
InsertSBT(T,str[i]);
}
}
/**
* ---------查找--------
* @param T
* @param elm
* @param p
* @return
*/
BiTree SearchBST(BiTree T,ElemType elm,BiTree p){
p=NULL;
while(T!=NULL && elm!=T->data){
p=T;
if(elm<T->data){
T=T->lchild;
} else if(elm>T->data){
T=T->rchild;
}
}
return T;
}
/**
* ----删除----
* @param T
* @param elm
*/
void DeleteBST(BiTree &T,ElemType elm){
if(T==NULL){
return;
}
if(T->data<elm){
DeleteBST(T->rchild,elm);
} else if(T->data>elm){
DeleteBST(T->lchild,elm);
} else{//找到了
if(T->lchild==NULL){
BiTree repalce;
repalce=T;
T=T->rchild;
free(repalce);
}else if(T->rchild==NULL){
BiTree repalce;
repalce=T;
T=T->lchild;
free(repalce);
}else{
BiTree replace;
replace=T->lchild;
while(replace->rchild!=NULL){
replace=replace->rchild;
}
T->data=replace->data;
DeleteBST(T->lchild,replace->data);
}
}
}
/**
* -----中序遍历----
* @param T
*/
void InOrder(BiTree T){
if(T!=NULL){
InOrder(T->lchild);
printf("%3d",T->data);
InOrder(T->rchild);
}
}
int main() {
BiTree T=NULL;
ElemType str[7]={12,45,8,56,98,54,66};
CreatBST(T,str,7);
InOrder(T);
printf("\n");
BiTree parent,search;
search= SearchBST(T,12,parent);
if(search){
printf("Y %d\n",search->data);
} else{
printf("N\n");
}
DeleteBST(T,98);
InOrder(T);
printf("\n");
return 0;
}
二叉排序树(二叉查找树)-C\C++
最新推荐文章于 2024-09-10 22:35:25 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)