二叉排序树的实现C++
时间: 2023-12-29 13:25:09 浏览: 74
二叉排序树C++实现
以下是二叉排序树的C++实现:
```cpp
#include<iostream>
using namespace std;
//树节点类定义
class TNode {
public:
int data;
TNode* left, * right;
TNode(int d) :left(nullptr), right(nullptr), data(d) {}
TNode() :left(nullptr), right(nullptr) {}
};
//二叉排序树类定义
class BST {
public:
TNode* root;
BST() :root(nullptr) {}
//插入节点
void insert(int data) {
TNode* node = new TNode(data);
if (root == nullptr) {
root = node;
return;
}
TNode* cur = root;
while (true) {
if (data < cur->data) {
if (cur->left == nullptr) {
cur->left = node;
return;
}
cur = cur->left;
}
else {
if (cur->right == nullptr) {
cur->right = node;
return;
}
cur = cur->right;
}
}
}
//查找节点
TNode* search(int data) {
TNode* cur = root;
while (cur != nullptr) {
if (data == cur->data) {
return cur;
}
else if (data < cur->data) {
cur = cur->left;
}
else {
cur = cur->right;
}
}
return nullptr;
}
//删除节点
void remove(int data) {
root = remove(root, data);
}
private:
//删除节点的辅助函数
TNode* remove(TNode* node, int data) {
if (node == nullptr) {
return nullptr;
}
if (data < node->data) {
node->left = remove(node->left, data);
}
else if (data > node->data) {
node->right = remove(node->right, data);
}
else {
if (node->left == nullptr) {
TNode* right = node->right;
delete node;
return right;
}
if (node->right == nullptr) {
TNode* left = node->left;
delete node;
return left;
}
TNode* minNode = findMin(node->right);
node->data = minNode->data;
node->right = remove(node->right, minNode->data);
}
return node;
}
//查找最小节点
TNode* findMin(TNode* node) {
while (node->left != nullptr) {
node = node->left;
}
return node;
}
};
//测试
int main() {
BST bst;
bst.insert(5);
bst.insert(3);
bst.insert(7);
bst.insert(1);
bst.insert(4);
bst.insert(6);
bst.insert(8);
TNode* node = bst.search(4);
if (node != nullptr) {
cout << "Found: " << node->data << endl;
}
else {
cout << "Not found" << endl;
}
bst.remove(3);
node = bst.search(3);
if (node != nullptr) {
cout << "Found: " << node->data << endl;
}
else {
cout << "Not found" << endl;
}
return 0;
}
```
阅读全文