二叉排序树BST
二叉排序树BST
一. SearchBST(T, key)
伪代码
void SearchBST(BiTree& T, int key) {
if (T为空)
cout<<"没有该元素";
else if (T->data == key)
cout<< "查找成功";
else if (key < T->data)
递归查找左子树;
else
递归查找右子树;
}
代码实现
void SearchBST(BiTree& T, int key) {
if (T == NULL)
cout<<"没有该元素";
else if (T->data == key)
cout<< "查找成功";
else if (key < T->data)
SearchBST(T->lchild, key);
else
SearchBST(T->rchild, key);
}
二. InsertBST(T, key)
伪代码:
void InsertBST(BiTree& T, int key)
{
if (T为空)
{
创建一个新节点T;
T->data == key;
T->lchild = T->rchild = NULL;
}
else if (T->data == key)
输出错误;
else if (T->data > key)
InsertBST(T->lchild, key);
else
InsertBST(T->rchild, key);
}
代码实现:
void InsertBST(BiTree& T, int key)
{
if (T == NULL)
{
T = new BiTNode;
T->data = key;
T->lchild = T->rchild = NULL;
}
else if (T->data == key)
cout << "此数存在";
else if (T->data > key)
InsertBST(T->lchild, key);
else
InsertBST(T->rchild, key);
}
三. CreateBST(T)
伪代码:
void CreateBST(BiTree &T)
{
输入二叉排序树节点个数n;
int a[n];
cout << "输入数据,中间空格";
for (int i = 0;i < n;i++)
{
cin >> a[i];
InsertBST(T, a[i]);
}
}
代码实现:
void CreateBST(BiTree &T)
{
int n;
cout<< "输入添加的节点个数"<<endl;
cin >> n;
int a[100];
cout << "输入数据,中间空格"<<endl;
for (int i = 0;i < n;i++)
{
cin >> a[i];
InsertBST(T, a[i]);
}
}
四. DeleteBST(T, key)
伪代码:
void DeleteBST(BiTree &T, int key)
{
if (!T)
cout << "error";
else
{
if (T->data == key)
{
删除节点;//分三种情况
{
BiTree q, s;
if (没有左孩子)
{
q = T;
T指向右孩子;
删除q节点;
}
else if (没有右孩子)
{
q = T;
T指向左孩子;
删除q节点;
}
else//两个孩子都有
{
q = T;
s = q->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
T->data = s->data;
if (q != T)
{
q->rchild = s->lchild;
}
else
{
q->lchild = s->lchild;
}
delete s;
}
}
cout << "删除成功";
}
else if (key < T->data)
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
代码实现:
void DeleteBST(BiTree &T, int key)
{
if (!T)
cout << "error"<<endl;
else
{
if (T->data == key)
{
//删除节点分三种情况
{
BiTree q, s;
if (!T->lchild)
{
q = T;
T = T->rchild;
delete q;
}
else if (!T->rchild)
{
q = T;
T = T->lchild;
delete q;
}
else//两个孩子都有
{
q = T;
s = q->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
T->data = s->data;
if (q != T)
{
q->rchild = s->lchild;
}
else
{
q->lchild = s->lchild;
}
delete s;
}
}
cout << "删除成功"<<endl;
}
else if (key < T->data)
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
五.主函数部分与中序遍历
void midOrderTraverse(BiTree T)
{
if (T)
{
midOrderTraverse(T->lchild);
cout << T->data << " ";
midOrderTraverse(T->rchild);
}
}
int main()
{
BiTree T = NULL;
CreateBST(T);
midOrderTraverse(T);
cout << endl;
int n;
cout << "删除的元素大小"<<endl;
cin >> n;
DeleteBST(T, n);
midOrderTraverse(T);
}
六.运行结果展示




浙公网安备 33010602011771号