二叉排序树的实现与基本操作 功能1:二叉排序树的建立; 功能2:二叉排序树的删除; 功能3:二叉排序树的中序遍历结果。用DEV C++软件写编程
时间: 2024-01-03 21:22:42 浏览: 95
以下是使用DEV C++软件编写的二叉排序树的实现与基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉排序树的结点结构
typedef struct BSTNode {
int data; // 结点数据
struct BSTNode *left; // 左子树指针
struct BSTNode *right; // 右子树指针
} BSTNode;
// 创建新结点
BSTNode* createNode(int data) {
BSTNode* newNode = (BSTNode*)malloc(sizeof(BSTNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 向二叉排序树中插入结点
BSTNode* insertNode(BSTNode* root, int data) {
if (root == NULL) {
return createNode(data);
} else if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
// 在二叉排序树中查找结点
BSTNode* searchNode(BSTNode* root, int data) {
if (root == NULL || root->data == data) {
return root;
} else if (data < root->data) {
return searchNode(root->left, data);
} else {
return searchNode(root->right, data);
}
}
// 删除二叉排序树中的结点
BSTNode* deleteNode(BSTNode* root, int data) {
if (root == NULL) {
return root;
} else 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) {
BSTNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
BSTNode* temp = root->left;
free(root);
return temp;
}
// 有两个子结点的情况
BSTNode* temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
// 中序遍历二叉排序树
void inorderTraversal(BSTNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
int main() {
BSTNode* root = NULL;
int choice, data;
do {
printf("1. 插入结点\n");
printf("2. 删除结点\n");
printf("3. 中序遍历\n");
printf("0. 退出\n");
printf("请输入您的选择:");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入要插入的结点数据:");
scanf("%d", &data);
root = insertNode(root, data);
break;
case 2:
printf("请输入要删除的结点数据:");
scanf("%d", &data);
root = deleteNode(root, data);
break;
case 3:
printf("中序遍历结果:");
inorderTraversal(root);
printf("\n");
break;
case 0:
printf("程序已退出。\n");
break;
default:
printf("无效的选择,请重新输入。\n");
break;
}
} while (choice != 0);
return 0;
}
```
阅读全文
相关推荐



















