C 语言中二叉查找树怎么实现?
时间: 2023-03-25 19:00:34 浏览: 115
BinarySearchTree:Java中二叉搜索树的实现
C语言中二叉查找树可以通过定义一个结构体来实现。结构体包含一个指向左子树和右子树的指针,以及一个存储数据的变量。具体实现过程如下:
1. 定义结构体
```
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
```
2. 插入节点
```
void insert(struct TreeNode** root, int data) {
if (*root == NULL) {
*root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
(*root)->data = data;
(*root)->left = NULL;
(*root)->right = NULL;
} else if (data < (*root)->data) {
insert(&((*root)->left), data);
} else if (data > (*root)->data) {
insert(&((*root)->right), data);
}
}
```
3. 查找节点
```
struct TreeNode* search(struct TreeNode* root, int data) {
if (root == NULL || root->data == data) {
return root;
} else if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
```
4. 删除节点
```
struct TreeNode* delete(struct TreeNode* root, int data) {
if (root == NULL) {
return root;
} else if (data < root->data) {
root->left = delete(root->left, data);
} else if (data > root->data) {
root->right = delete(root->right, data);
} 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 = minValueNode(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
return root;
}
```
5. 找到最小值节点
```
struct TreeNode* minValueNode(struct TreeNode* node) {
struct TreeNode* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
```
阅读全文