二叉排序树的基本操作代码
时间: 2023-08-21 21:33:36 浏览: 74
二叉排序树的基本操作
下面是二叉排序树的基本操作代码,包括插入、查找、删除等操作:
```c++
#include<iostream>
using namespace std;
struct BSTreeNode {
int val;
BSTreeNode* left;
BSTreeNode* right;
BSTreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTree {
public:
BSTree() : root(NULL) {}
bool insert(int val) { // 插入节点
if (!root) {
root = new BSTreeNode(val);
return true;
}
BSTreeNode* cur = root;
while (cur) {
if (cur->val == val) {
return false; // 已存在该节点
} else if (cur->val < val) {
if (!cur->right) {
cur->right = new BSTreeNode(val);
return true;
}
cur = cur->right;
} else {
if (!cur->left) {
cur->left = new BSTreeNode(val);
return true;
}
cur = cur->left;
}
}
return false;
}
bool search(int val) { // 查找节点
BSTreeNode* cur = root;
while (cur) {
if (cur->val == val) {
return true;
} else if (cur->val < val) {
cur = cur->right;
} else {
cur = cur->left;
}
}
return false;
}
bool remove(int val) { // 删除节点
BSTreeNode* cur = root;
BSTreeNode* parent = NULL;
while (cur && cur->val != val) {
parent = cur;
if (cur->val < val) {
cur = cur->right;
} else {
cur = cur->left;
}
}
if (!cur) {
return false; // 不存在该节点
}
if (cur->left && cur->right) { // 节点存在左右子树
BSTreeNode* tmp = cur->right;
while (tmp->left) {
tmp = tmp->left;
}
cur->val = tmp->val;
cur = tmp;
parent = cur->right;
}
BSTreeNode* child;
if (cur->left) {
child = cur->left;
} else if (cur->right) {
child = cur->right;
} else {
child = NULL;
}
if (!parent) {
root = child;
} else if (parent->left == cur) {
parent->left = child;
} else {
parent->right = child;
}
delete cur;
return true;
}
private:
BSTreeNode* root;
};
```
在二叉排序树中,每个节点都有一个唯一的键值,且左子树中所有节点的键值小于根节点的键值,右子树中所有节点的键值大于根节点的键值。这个代码中定义了两个结构体,一个表示节点,一个表示二叉排序树。在二叉排序树中,插入节点、查找节点、删除节点等操作都需要满足这个性质。
阅读全文