用c++实现① 二叉排序树的建立; ② 二叉排序树的查找; ③ 二叉排序树的插入; ④ 二叉排序树的删除; ⑤ 二叉排序树的销毁;
时间: 2024-01-10 22:22:07 浏览: 84
以下是用C++实现二叉排序树的建立、查找、插入、删除和销毁的示例代码:
1. 二叉排序树的建立:
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
TreeNode* buildBST(int arr[], int n) {
TreeNode* root = NULL;
for (int i = 0; i < n; i++) {
root = insert(root, arr[i]);
}
return root;
}
```
2. 二叉排序树的查找:
```cpp
TreeNode* search(TreeNode* root, int val) {
if (root == NULL || root->val == val) {
return root;
}
if (val < root->val) {
return search(root->left, val);
} else {
return search(root->right, val);
}
}
```
3. 二叉排序树的插入:
```cpp
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
```
4. 二叉排序树的删除:
```cpp
TreeNode* findMin(TreeNode* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}
TreeNode* deleteNode(TreeNode* root, int val) {
if (root == NULL) {
return root;
}
if (val < root->val) {
root->left = deleteNode(root->left, val);
} else if (val > root->val) {
root->right = deleteNode(root->right, val);
} else {
if (root->left == NULL) {
TreeNode* temp = root->right;
delete root;
return temp;
} else if (root->right == NULL) {
TreeNode* temp = root->left;
delete root;
return temp;
}
TreeNode* temp = findMin(root->right);
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
```
5. 二叉排序树的销毁:
```cpp
void destroyBST(TreeNode* root) {
if (root == NULL) {
return;
}
destroyBST(root->left);
destroyBST(root->right);
delete root;
}
```
阅读全文