#include “stdio.h”
#include “math.h”
//二叉排序树
typedef struct BiTNode//结点结构
{
int data;
struct BiTNode *lchild, *rchild;
}BiTNode,*BiTNree;
//递归查找二叉排序树T中是否存在key
//指针f指向T的双亲,其初始调用值为null
//如果查找成功,指针p指向这个元素结点,返回ture,否则指针p指向查找路径上的最后一个结点并且返回false
int SearchBST(BiTNree T, int key, BiTNree f, BiTNree *p)
{
if (!T)//查找不成功
{
*p = f;
return false;
}
else if (key == T->data)
{
*p = T;
return true;
}
else if (key < T->data)
return SearchBST(T->lchild, key, T, p);
else
return SearchBST(T->rchild, key, T, p);
}
//二叉排序树的插入操作
//当二叉排序树中不存在关键字等于key的数据元素时,插入key并返回true,否则就返回false
int InsertBST(BiTNree *T, int key)
{
BiTNree p,s;
if (!SearchBST(*T, key, NULL, &p))//查找不成功
{
s = (BiTNree*)malloc(sizeof(BiTNree));
s->data = key;
s->lchild = s->rchild = NULL;
if (!p)
*T = s;//插入s为新的根节点
else if (key < p->data)
p->lchild = s;
else
p->rchild = s;
return true;
}
else
return false;
}
int main()
{
int i;
int a[10] = { 62, 88, 58, 47, 35, 73, 51, 99, 37, 93 };
BiTree T = NULL;
for (i = 0; i < 0; i++)
{
InsertBST(&T, a[i]);
}
}
//如果二叉排序树T中存在关键字等于key的数据元素时,就删除这个元素结点并且返回true,否则返回false
int DeleteBST(BiTree *T, int key)
{
if (!*T)//不存在关键字等于key的数据元素
return false;
else
{
if (key == (*T)->data)//找到关键字等于key的数据元素
return DELETE(T);
else if (key < (*T)->data)
return DeleteBST((*T)->lchild, key);
else
return DeleteBST((*T)->rchild, key);
}
}
int Delete(BiTree *p)
{
BITree q, s;
if ((*p)->rchild == NULL)//右子树空就只需要重接它的左子树
{
q = *p; *p = (*p)->lchild; free(q)
}
else if ((*p)->lchild == NULL)//左子树空就只需要重接它的右子树
{
q = *p; *p = (*p)->rchild; free(q);
}
else//左右子树都不空
{
q = *p; s = (*p)->lchild;
while (s->rchild)//转左,然后向右到尽头(找到待删结点的前驱)
{
q = s; s = s->rchild;
}
(*p)->data = s->data;//s指向被删结点的直接前驱
if (q != *p)
q->rchild = s->lchild;//重接q的右子树
else
q->lchild = s->lchild;//重接q的左子树
free(s);
}
return true;
}