#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct BiTNode
{
int data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
bool searchBST(BiTree T, int key, BiTree f, BiTree *p)
{
//指针f指向T的双亲,其初始调用值为NULL
//若查找成功,则指针p指向该数据元素结点,并返回true。
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);
}
bool 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)->lchild == NULL)
{
q = (*p);
*p = (*p)->rchild;
free(q);
}
else if ((*p)->rchild == NULL)
{
q = (*p);
*p = (*p)->lchild;
free(q);
}
else
{
q = *p;
s = (*p)->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
(*p)->data = s->data;
if (q != *p)
{
q->rchild = s->lchild;
}
else
q->lchild = s->lchild;
free(s);
}
return true;
}
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);
}
}
void preTraverse(BiTree T)
{
if (T == NULL)
{
return;
}
preTraverse((T)->lchild);
cout<<(T)->data<<" ";
preTraverse((T)->rchild);
}
int main()
{
int i;
int a[10] = {62, 88, 58, 47, 35, 73, 51, 99, 37, 93};
BiTree T = NULL;
for (i = 0; i < 10; i++)
{
insertBST(&T, a[i]);
}
// BiTree* p = & T->rchild;
// *p = (*p)->rchild;
// cout<<(*p)->data<<endl;
preTraverse(T);
cout<<endl;
DeleteBST(&T, 37);
cout<<"------------after delete bst-------------"<<endl;
preTraverse(T);
cout<<endl;
}
二叉搜索树的一些基本操作
最新推荐文章于 2022-10-19 21:21:23 发布