首先编程实现读入一串字符创建一棵二叉排序树,然后分别实现:二叉排序树的查找;二叉排序树的插入;二叉排序树的删除等操作。用C语言
时间: 2023-12-08 20:38:38 浏览: 92
以下是C语言实现读入一串字符创建一棵二叉排序树,以及二叉排序树的查找、插入、删除操作的代码:
1. 读入一串字符创建一棵二叉排序树
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 插入节点
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
// 创建二叉排序树
TreeNode* createBST(int n) {
TreeNode* root = NULL; int val;
for (int i = 0; i < n; i++) {
scanf("%d", &val);
root = insert(root, val);
}
return root;
}
```
2. 二叉排序树的查找
```c
// 查找节点
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. 二叉排序树的插入
```c
// 插入节点
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
```
4. 二叉排序树的删除
```c
// 删除节点
TreeNode* delete(TreeNode* root, int val) {
if (root == NULL) {
return root;
}
if (val < root->val) {
root->left = delete(root->left, val);
} else if (val > root->val) {
root->right = delete(root->right, val);
} else {
if (root->left == NULL) {
TreeNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
TreeNode* temp = root->left;
free(root);
return temp;
}
TreeNode* temp = root->right;
while (temp->left ! NULL) {
temp = temp->left;
}
root->val = temp->val;
root->right = delete(root->right, temp->val);
}
return root;
}
```
阅读全文