C语言写一个,二叉树算法
时间: 2023-12-15 08:53:29 浏览: 75
以下是C语言实现的二叉树算法:
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
struct TreeNode {
int value;
struct TreeNode* left;
struct TreeNode* right;
};
//二叉树的创建和初始化
struct TreeNode* create(int value) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
//二叉树的插入操作
struct TreeNode* insert(struct TreeNode* root, int value) {
if (root == NULL) {
return create(value);
}
if (value < root->value) {
root->left = insert(root->left, value);
} else {
root->right = insert(root->right, value);
}
return root;
}
//二叉树的查找操作
struct TreeNode* search(struct TreeNode* root, int value) {
if (root == NULL || root->value == value) {
return root;
}
if (value < root->value) {
return search(root->left, value);
} else {
return search(root->right, value);
}
}
//二叉树的遍历操作
void preorder(struct TreeNode* root) {
if (root != NULL) {
printf("%d ", root->value);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct TreeNode* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->value);
inorder(root->right);
}
}
void postorder(struct TreeNode* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->value);
}
}
//二叉树的删除操作
struct TreeNode* delete(struct TreeNode* root, int value) {
if (root == NULL) {
return root;
}
if (value < root->value) {
root->left = delete(root->left, value);
} else if (value > root->value) {
root->right = delete(root->right, value);
} 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 = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->value = temp->value;
root->right = delete(root->right, temp->value);
}
return root;
}
int main() {
struct TreeNode* root = NULL;
root = insert(root, 5);
root = insert(root, 3);
root = insert(root, 7);
root = insert(root, 2);
root = insert(root, 4);
root = insert(root, 6);
root = insert(root, 8);
printf("Preorder traversal: ");
preorder(root);
printf("\n");
printf("Inorder traversal: ");
inorder(root);
printf("\n");
printf("Postorder traversal: ");
postorder(root);
printf("\n");
root = delete(root, 3);
printf("Inorder traversal after deletion: ");
inorder(root);
printf("\n");
return 0;
}
```
在上面的代码中,我们定义了一个二叉树结构体,包含了一个节点值和左右子树指针。然后我们实现了二叉树的创建、插入、查找、遍历和删除操作。在主函数中,我们创建了一个二叉树,并对其进行遍历和删除操作。
阅读全文