根据二叉排序树的抽象数据类型的定义,使用二叉链表实现一个二叉排序树。二叉排序树的基本功能:1、二叉排序树的建立;2、二叉排序树的查找;3、二叉排序树的插入;4、二叉排序树的删除;5、二叉排序树的销毁;6、其他:自定义操作。编写测试main()函数测试二叉排序树的正确性。
时间: 2023-10-13 09:26:36 浏览: 137
好的,以下是使用二叉链表实现二叉排序树的代码实现,并附带测试main()函数。
```c++
#include <iostream>
using namespace std;
// 定义二叉排序树的结构体
typedef struct BSTNode{
int data;
struct BSTNode* left;
struct BSTNode* right;
}BSTNode, *BSTree;
// 初始化二叉排序树
void InitBSTree(BSTree &T) {
T = NULL;
}
// 创建二叉排序树
void CreateBSTree(BSTree &T, int a[], int n) {
for (int i = 0; i < n; i++) {
BSTNode* p = new BSTNode;
p->data = a[i];
p->left = NULL;
p->right = NULL;
// 插入节点
if (T == NULL) {
T = p;
} else {
BSTNode* q = T;
while (true) {
if (p->data < q->data) {
if (q->left == NULL) {
q->left = p;
break;
} else {
q = q->left;
}
} else {
if (q->right == NULL) {
q->right = p;
break;
} else {
q = q->right;
}
}
}
}
}
}
// 查找二叉排序树中是否有指定元素
BSTNode* SearchBSTree(BSTree T, int key) {
if (T == NULL || T->data == key) {
return T;
} else if (key < T->data) {
return SearchBSTree(T->left, key);
} else {
return SearchBSTree(T->right, key);
}
}
// 插入元素到二叉排序树
bool InsertBSTree(BSTree &T, int key) {
if (T == NULL) {
BSTNode* p = new BSTNode;
p->data = key;
p->left = NULL;
p->right = NULL;
T = p;
return true;
} else if (T->data == key) {
return false; // 已存在相同元素
} else if (key < T->data) {
return InsertBSTree(T->left, key);
} else {
return InsertBSTree(T->right, key);
}
}
// 删除二叉排序树中指定元素
bool DeleteBSTree(BSTree &T, int key) {
if (T == NULL) {
return false;
} else if (key < T->data) {
return DeleteBSTree(T->left, key);
} else if (key > T->data) {
return DeleteBSTree(T->right, key);
} else {
if (T->left == NULL && T->right == NULL) {
delete T;
T = NULL;
} else if (T->left == NULL) {
BSTNode* p = T;
T = T->right;
delete p;
} else if (T->right == NULL) {
BSTNode* p = T;
T = T->left;
delete p;
} else {
BSTNode* p = T->right;
while (p->left != NULL) {
p = p->left;
}
T->data = p->data;
DeleteBSTree(T->right, p->data);
}
return true;
}
}
// 销毁二叉排序树
void DestroyBSTree(BSTree &T) {
if (T != NULL) {
DestroyBSTree(T->left);
DestroyBSTree(T->right);
delete T;
T = NULL;
}
}
// 自定义操作:中序遍历并输出二叉排序树的所有节点值
void PrintBSTree(BSTree T) {
if (T != NULL) {
PrintBSTree(T->left);
cout << T->data << " ";
PrintBSTree(T->right);
}
}
int main() {
BSTree T;
InitBSTree(T);
int a[] = {6, 3, 8, 2, 5, 7, 9};
CreateBSTree(T, a, 7);
// 测试查找
BSTNode* node = SearchBSTree(T, 5);
if (node != NULL) {
cout << "find " << node->data << endl;
} else {
cout << "not find" << endl;
}
// 测试插入
bool res = InsertBSTree(T, 4);
if (res) {
cout << "insert success" << endl;
} else {
cout << "insert fail" << endl;
}
// 测试删除
res = DeleteBSTree(T, 5);
if (res) {
cout << "delete success" << endl;
} else {
cout << "delete fail" << endl;
}
// 打印二叉排序树
PrintBSTree(T);
// 销毁二叉排序树
DestroyBSTree(T);
return 0;
}
```
输出结果:
```
find 5
insert success
delete success
2 3 4 6 7 8 9
```
阅读全文