用c语言 首先编程实现读入一串字符创建一棵二叉排序树,然后分别实现:二叉排序树的查找;二叉排序树的插入;二叉排序树的删除等操作。
时间: 2023-12-21 08:31:22 浏览: 83
C语言实现二叉树的创建、插入、删除、遍历等操作
5星 · 资源好评率100%
```c
// 读入一串字符创建一棵二叉排序树
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* insert(TreeNode* root, char data) {
if (root == NULL) {
TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
TreeNode* search(TreeNode* root, char data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
TreeNode* minValueNode(TreeNode* node) {
TreeNode* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
TreeNode* deleteNode(TreeNode* root, char data) {
if (root == NULL) {
return root;
}
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} 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 = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
int main() {
TreeNode* root = NULL;
char input[100];
printf("请输入一串字符:");
scanf("%s", input);
for (int i = 0; i < strlen(input); i++) {
root = insert(root, input[i]);
}
// 进行查找、插入、删除操作
// 例如:TreeNode* result = search(root, 'a');
// root = insert(root, 'z');
// root = deleteNode(root, 'b');
return 0;
}
```
阅读全文