typedef struct BTNode {
KeyType Key;
InfoType data;
struct BTNode* lchild, * rchild;
}*BSTNode,BSTnode;
伪代码:
void SearchBST(BSTNode T,int key)
{
if(T为空||T的关键字==key)
return;
if(key<T的关键字)
SearchBST(T->lchild, key);
else
SearchBST(T->rchild, key);
}
void InsertBST(BSTNode &T,int key)
{
if(T为空)
{
T=new BiTreeNode();
将key存入T节点中;
T的左右孩子为空;
return;
}
else if(key等于T的关键字)
return;
else if(key小于T的关键字)
InsertBST(T->lchild, key);
else
InsertBST(T->rchild, key);
}
代码
void SearchBST(BSTNode T, int key)
{
if (T == NULL || T->Key == key)
return;
else if (key < T->Key)
SearchBST(T->lchild, key);
else
SearchBST(T->rchild, key);
}
void InserBST(BSTNode T, int key)
{
if (T == NULL)
{
T = new BSTnode();
T->Key = key;
T->lchild = T->rchild = NULL;
return;
}
else if (T->Key == key)
return;
else if (key < T->Key)
InserBST(T->lchild, key);
else
InserBST(T->rchild, key);
}
伪代码
void CreateBST(T)
{
int a[100],j;
for(int i=0;a[i];i++)
cin>>a[i];
while(j小于i)
{
调用插入函数InserBST(T,a[i]);
j++;
}
return;
}
代码
void CreateBST(BSTNode &T)
{
int a[100], j, i, n;
j = i = 0;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
while (j<i)
{
InserBST(T, a[j]);
j++;
}
return;
}
运行输出
伪代码
DeleteBST(T, key)
{
if(T为空)
return;
if(key<T->Key)
DeleteBST(T->lchild,key);
else if(key>T->Key)
DeleteBST(T->rchild,key);
else
{
调用Delete(T)删除T节点;
return;
}
}
Delete(p)
{
BSTNode q;
if(p的右子树为空)
{
q=p;
p=p->lchild;
释放q节点;
}
else if(p的左子树为空)
{
q=p;
p=p->rchild;
释放q节点;
}
else
调用Delete1(p,p->lchild)删除既有左子树又有右子树的节点p
}
Delete1(p,r)
{
BSTNode q;
if(r的右子树为空)
递归调用Delete1(p,r->rchild)找到前驱节点;
else
{
p->Key=r->Key;
q=r;r=r->lchild;
释放q节点;
}
}
void DeleteBST(BSTNode &T,int key)
{
if(T==NULL)
return;
if(key<T->Key)
DeleteBST(T->lchild,key);
else if(key>T->Key)
DeleteBST(T->rchild,key);
else
{
Delete(T);
return;
}
}
void Delete(BSTNode &p)
{
BSTNode q;
if(p->rchild==NULL)
{
q=p;
p=p->lchild;
free(q);
}
else if(p->lchild==NULL)
{
q=p;
p=p->rchild;
free(q);
}
else
Delete1(p,p->lchild);
}
void Delete1(BSTNode &p,BSTNode &r)
{
BSTNode q;
if(r->rchild==NULL)
Delete1(p,r->rchild);
else
{
p->Key=r->Key;
q=r;r=r->lchild;
free(q);
}
}
原文:https://www.cnblogs.com/zhanyb/p/12733479.html