标签:com i++ 使用 ++ else src 数据量 排序 pre
查找
//伪代码
SearchBST(T, key)
{
if (T为空 || T->key == key)
return T;
if (key > T->key)
return SearchBST(T->rchild, key);
else
return SearchBST(T->lchild, key);
}
//代码实现
BSTree SearchBST(BSTree T,int key)
{
if (T == NULL || T->key == key)
return T;
if (key > T->key)
return SearchBST(T->rchild, key);
else
return SearchBST(T->lchild, key);
}
插入
//伪代码
InsertBST(T, key)
{
if(T为空)
{
T->key = key;
T->lchild = T->rchild = NULL;
}
else if (key == T->key)
return;
else if(key > T->key)
Insert(T->rchild, key);
else
Insert(T->lchild, key);
}
//代码实现
void InsertBST(BSTree &T,int key)
{
if(T == NULL)
{
T = new BSTNode;
T->key = key;
T->lchild = T->rchild = NULL;
}
else if (key == T->key)
return;
else if(key > T->key)
InsertBST(T->rchild, key);
else
InsertBST(T->lchild, key);
}
创建
//伪代码
CreateBST(n) //n为输入的数据量
{
for (i = 0; i<n; i++)
{
cin >> key;
InsertBST(T, key);
}
return T;
}
//代码实现
BSTree CreateBST(int n)
{
BSTree T = NULL;
int key;
for (int i = 0; i<n; i++)
{
cin >> key;
InsertBST(T, key);
}
return T;
}
输出效果:
//伪代码
DeleteBST(T, key)
{
if (T为空)
{
return;
}else
{
if (key < T->key)
{
DeleteBST(T->lchild, key);
}
else if (key > T->key)
{
DeleteBST(T->rchild, key);
}else
{
DeleteT(T); //调用删除结点函数
}
}
}
DeleteT(T)
{
if (T->rchild 为空)
{
p = T;
T = T->lchild;
删除结点p;
}else if (T->lchild 为空)
{
p = T;
T = T->rchild;
删除结点p;
}else
{
DeleteTree(T,T->lchild); //结点p左右子树均存在时,调用另一删除函数
}
}
DeleteTree(T,r)
{
if (r->rchild 不为空)
{
DeleteTree(T,r->rchild); //找到最右结点
}else
{
T->key = r->key;
p = r;
r = r->lchild;
删除结点p;
}
}
//代码实现
void DeleteBST(BSTree &T,int key)
{
if (T == NULL)
{
return;
}else
{
if (key < T->key)
{
DeleteBST(T->lchild, key);
}
else if (key > T->key)
{
DeleteBST(T->rchild, key);
}else
{
DeleteT(T); //调用删除结点函数
}
}
}
void DeleteT(BSTree &T)
{
BSTree p;
if (T->rchild == NULL)
{
p = T;
T = T->lchild;
delete p;
}else if (T->lchild == NULL)
{
p = T;
T = T->rchild;
delete p;
}else
{
DeleteTree(T,T->lchild); //结点p左右子树均存在时,调用另一删除函数
}
}
void DeleteTree(BSTree &T,BSTree &r)
{
BSTree p;
if (r->rchild)
{
DeleteTree(T,r->rchild);
}else
{
T->key = r->key;
p = r;
r = r->lchild;
delete p;
}
}
效果(删除30):
标签:com i++ 使用 ++ else src 数据量 排序 pre
原文地址:https://www.cnblogs.com/wzt392217419/p/12731208.html