C语言任务二:二叉排序树的实现与基本操作 功能1:二叉排序树的建立; 功能2:二叉排序树的删除; 功能3:二叉排序树的中序遍历结果。
时间: 2023-12-31 09:24:54 浏览: 72
二叉树的几种操作,包括递归先序建立二叉树、先序遍历、中序遍历、后序遍历、非递归的各种遍历
5星 · 资源好评率100%
以下是C语言实现二叉排序树的基本操作的示例代码:
1. 二叉排序树的建立:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* insert(struct TreeNode* root, int val) {
if (root == NULL) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
if (val < root->val) {
root->left = insert(root->left, val);
} else if (val > root->val) {
root->right = insert(root->right, val);
}
return root;
}
```
2. 二叉排序树的删除:
```c
struct TreeNode* delete(struct TreeNode* root, int val) {
if (root == NULL) {
return NULL;
}
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) {
struct TreeNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct TreeNode* temp = root->left;
free(root);
return temp;
}
struct TreeNode* temp = findMin(root->right);
root->val = temp->val;
root->right = delete(root->right, temp->val);
}
return root;
}
struct TreeNode* findMin(struct TreeNode* node) {
while (node->left != NULL) {
node = node->left;
}
return node;
}
```
3. 二叉排序树的中序遍历结果:
```c
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
```
阅读全文