二叉排序树
2021-02-11 21:19
标签:节点 turn creat null 它的 ebs lan else 左右 SearchBST(T,key)伪代码: InsertBST(T,key)伪代码: 实现: 代码: 运行结果: 伪代码: 实现: 伪代码: 明天早上看可以吗(╥ω╥`) 非常感谢!!!!! 二叉排序树 标签:节点 turn creat null 它的 ebs lan else 左右 原文地址:https://www.cnblogs.com/599-/p/12734027.html1.编写SearchBST(T,key),InsertBST(T,key)伪代码与实现
InsertBST(T, key)
{
if (T空 || T->key == key)
return T;
if(key
InsertBST(T, key) {
if (T空)
{
T = new BSTNode;
T->key = key;
T->lchild= T->rchild=NULL;
}
else if (key == T->key)
return;
else if (k key)
return InsertBST(T->lchild, key);
else
return InsertBST(T->rchild, key)
}
BSTNode* SearchBST(BSTNode* T, KeyType key)
{
if (T == NULL || T->key == key)
return T;
if (key key)
return SearchBST(T->lchild, key);
else
return SearchBST(T->rchild, key);
}
bool InsertBST(BSTNode* T, KeyType key)
{
if (T == NULL)
{
T = new BSTNode;
T->key = key;
T->lchild = T->rchild = NULL;
}
else if (key == T->key)
return false;
else if (key key)
return Insert(T->lchild, key);
else
return Insert(T->rchild, key);
}
2.编写CreateBST(T)的伪代码与实现
CreateBST(A[], n)
{
BSTNode* T = NULL;
int i = 0;
while (i
BSTNode* CreateBST(KeyType A[], int n)
{
BSTNode* T = NULL;
int i = 0;
while (i lchild);
cout key rchild);
}
}
3.编写DeleteBST(T,key)伪代码
DeleteBST( T, key)
{
if (!T)
return false;
else
{
if (key == T->key)
Delete(T)函数;
else if (key key)
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
int Delete(BSTNode* p)
{
BSTNode *q, *s;
if
(!p->lchild && !p->rchild)
p = NULL;
else if (!p->lchild)
{
q = p;
p = p->rchild;
delete q;
}
else if (p->rchild)
{
q = p;
p = p->lchild;
delete q;
}
else
{
q = p;
s = p->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
p->key = s->key;
if (q != p)
q->rchild = s->lchild;
else
q->lchild = s->lchild;
delete s;
}
return true;
}
4.代码实现DeleteBST(T,key)
int DeleteBST(BSTNode* T, KeyType key)
{
/* 若二叉排序树T中存在关键字等于key的数据元素时,则删除该数据元素节点 */
/* 并返回TRUE;否则返回FALSE */
if (!T)
return false;
/* 不存在关键字等于key的数据元素 */
else
{
if (key == T->key)
Deletel(T);
else if (key key)
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
int Deletel(BSTNode* p)//从二叉排序树中删除节点p, 并重接它的左或右子树
{
BSTNode *q, *s;
if
(!p->lchild && !p->rchild) // p为叶子节点
p = NULL; else if (!p->lchild) // 左子树为空,重接右子树
{
q = p;
p = p->rchild;
delete q;
}
else if
(p->rchild) // 右子树为空,重接左子树
{
q = p;
p = p->lchild;
delete q;
}
else // 左右子树均不为空
{
q = p;
s = p->lchild;
while (s->rchild) // 转左,向右走到尽头
{
q = s;
s = s->rchild;
}
p->key = s->key;
if (q != p) //判断是否执行上述while循环
q->rchild = s->lchild; // 执行上述while循环,重接右子树
else
q->lchild = s->lchild; // 未执行上述while循环,重接左子树
delete s;
}
return true;
}