给一个c语言实现二叉树
时间: 2023-11-18 10:43:50 浏览: 97
当然可以!以下是一个简单的 C 语言实现二叉树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
// 创建一个新的二叉树节点
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 向二叉树插入一个节点
struct TreeNode* insertNode(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
// 在二叉树中搜索一个节点
struct TreeNode* searchNode(struct TreeNode* root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return searchNode(root->left, data);
} else {
return searchNode(root->right, data);
}
}
// 删除二叉树中的一个节点
struct TreeNode* deleteNode(struct TreeNode* root, int 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) {
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 = deleteNode(root->right, temp->data);
}
return root;
}
// 找到二叉树中的最小值节点
struct TreeNode* minValueNode(struct TreeNode* node) {
struct TreeNode* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
// 遍历并打印二叉树(中序遍历)
void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
int main() {
struct TreeNode* root = NULL;
// 插入节点
root = insertNode(root, 50);
root = insertNode(root, 30);
root = insertNode(root, 20);
root = insertNode(root, 40);
root = insertNode(root, 70);
root = insertNode(root, 60);
root = insertNode(root, 80);
// 中序遍历并打印二叉树
printf("中序遍历结果:");
inorderTraversal(root);
printf("\n");
// 搜索节点
int searchData = 40;
struct TreeNode* searchResult = searchNode(root, searchData);
if (searchResult != NULL) {
printf("节点 %d 存在于二叉树中。\n", searchData);
} else {
printf("节点 %d 不存在于二叉树中。\n", searchData);
}
// 删除节点
int deleteData = 30;
root = deleteNode(root, deleteData);
printf("删除节点 %d 后的中序遍历结果:", deleteData);
inorderTraversal(root);
printf("\n");
return 0;
}
```
这个示例代码实现了二叉树的创建、插入、搜索和删除功能,并对二叉树进行了中序遍历以打印节点。你可以根据需要进行修改和扩展。希望对你有帮助!
阅读全文