用c++一段代码实现二叉排序树的建立;二叉排序树的查找;二叉排序树的插入; 二叉排序树的删除;二叉排序树的销毁;
时间: 2024-01-10 14:22:07 浏览: 80
用C++实现二叉树的建立,删除,添加。主要使用的是类的结构。....rar
以下是用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 destroy(TreeNode* root) {
if (root == NULL) {
return;
}
destroy(root->left);
destroy(root->right);
delete root;
}
```
阅读全文