/*
二叉排序树
VS2010
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OK 1
#define FALSE 0
#define ARRSIZE 10
typedef struct BitreeNode Bitree;
struct BitreeNode
{
int key;
Bitree *lchild;
Bitree *rchild;
};
/*
功能: 递归查找二叉排序树bstn中是否存在value
参数: father指向bstn的双亲,其初始调用值为NULL
返回: 查找成功,则指针p指向该数据元素结点,返回TRUE
查找失败,则指针p指向查找路径上访问的最后一个结点,返回FALSE
*/
int SearchBST(Bitree *bstn, int value, Bitree *father, Bitree **p)
{
if(NULL == bstn)
{
*p = father;
return FALSE;
}
if(value == bstn->key)
{
*p = bstn;
return OK;
}
else if(value < bstn->key)
{
return SearchBST(bstn->lchild, value, bstn, p); //在左子树中查找
}
else if(value > bstn->key)
{
return SearchBST(bstn->rchild, value, bstn, p); //在右子树中查找
}
}
/*
功能:向二叉排序树插入关键字为value的元素节点
返回:OK 插入成功;FALSE 已经存在该节点,没有插入
*/
int InsertBST(Bitree **bstn, int value)
{
Bitree *p = NULL;
Bitree *s = NULL;
if(SearchBST(*bstn, value, NULL, &p)) //已有该元素
{
return FALSE;
}
s = (Bitree *)malloc(sizeof(Bitree));
s->key = value;
s->lchild = s->rchild = NULL;
if(!p)
{
*bstn = s;
}
else if(value < p->)
{
p->lchild = s; //插为左孩子
}
else
{
p->rchild = s; //插为右孩子
}
return OK;
}
void CreateBST(Bitree **bstn)
{
int i = 0;
int arr[ARRSIZE] = {62,88,58,47,35,73,51,99,37,93};
for(i = 0; i < ARRSIZE; i++)
{
InsertBST(bstn, arr[i]);
}
return ;
}
int DeleteBTN(Bitree **bstn)
{
Bitree *p = NULL;
Bitree *s = NULL;
if((*bstn)->rchild == NULL) //如果右子树为空
{
p = *bstn;
*bstn = (*bstn)->lchild;
free(p);
}
else if((*bstn)->lchild == NULL) //如果左子树为空
{
p = *bstn;
*bstn = (*bstn)->rchild;
free(p);
}
else //左右子树均不为空
{
p = *bstn;
s = (*bstn)->rchild;
while(s->rchild) //找到待删除结点的前驱
{
p = s;
s = s->rchild;
}
(*bstn)->key = s->key;
if(p != (*bstn))
{
p->rchild = s->lchild;
}
else
{
p->lchild = s->lchild;
}
free(s);
}
return OK;
}
/*
功能:若二叉排序树bstn中存在关键字等于value的数据元素时,则删除该数据元素结点
返回:TRUE 成功删除;FALSE 否则返回
*/
int DeleteBST(Bitree **bstn, int value)
{
if(NULL == *bstn)
{
return FALSE;
}
if(value == (*bstn)->key)
{
DeleteBTN(bstn);
}
else if(value < (*bstn)->key)
{
return DeleteBST(&((*bstn)->lchild), value);
}
else
{
return DeleteBST(&((*bstn)->rchild), value);
}
return OK;
}
void PrintVal(int num)
{
printf("%d,", num);
}
//中序遍历打印数据,打印的便是从小到大排列的数据
int TravelBitree(Bitree *bstn)
{
if(!bstn)
{
return OK;
}
TravelBitree(bstn->lchild);
PrintVal(bstn->key);
TravelBitree(bstn->rchild);
return OK;
}
int main(int argc, char *argv[])
{
Bitree *btn = NULL;
CreateBST(&btn);
TravelBitree(btn);
printf("\b \n");
DeleteBST(&btn, 73);
TravelBitree(btn);
printf("\b \n");
system("pause");
return 0;
}