二叉排序树查找操作
typedef struct BiTNode
{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BOOL SearchBST(BiTree T, int key, BiTree f, BiTree *p)
{
if(!T){
*p = f;
return false;
}
else if (T->data == key){
*p = T;
return true;
}
else if (T->data < key)
return SearchBST(T->lchild, key, T, p);
else
return SearchBST(T->rchild, key, T, p);
}
二叉排序树插入操作
void InsertBST(BiTree *T, int key)
{
BiTree p, s;
if(!SearchBST( *T, key, NULL, &p))
{
s = (BiTree)malloc(sizeof(BiTNode));
s->data = key;
s->lchild = s->rchild = NULL;
if(!p)
*T = s;
else if(key < p->data)
p->lchild = s;
else
p->rchild = s;
return TRUE;
}
else
return FALSE;
}
二叉排序树删除操作
bool Delete(BiTree *p)
{
BiTree q,s;
if((*p)->child == NULL)
{
q = *p;
*p = (*p)->lchild;
free(q);
}
else if((*p)->child == NULL)
{
q = *p;
*p = (*p)->rchild;
free(q);
}
else
{
q = *p;
s = (*p)->lchild;
while(s->child){
q = s;
s = s->rchild;
}
(*p)->data = s->data;
if(q != *p)
q->rchild = s->lchild;
else
q->lchild = s->lchild;
free(s);
}
}
bool DeleteBST(BiTree *T, int key)
{
if(!*T)
return FALSE;
else
{
if(key == (*T)->data)
return Delete(T);
else if(key < (*T)->data)
return DeleteBST(&(*T)->lchild,key);
else
return DeleteBST(&(*T)->rchild,key);
}
}