应用二叉树的数据处理系统C语言实现代码
时间: 2023-10-26 19:04:12 浏览: 42
以下是一个简单的二叉树数据处理系统的 C 语言实现代码,包括二叉树的创建、遍历、查找等功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct node {
int data;
struct node *left;
struct node *right;
};
// 创建二叉树
struct node *createTree() {
struct node *root;
int data;
scanf("%d", &data);
if (data == -1) {
root = NULL;
} else {
root = (struct node *)malloc(sizeof(struct node));
root->data = data;
printf("Enter the left child of %d:\n", data);
root->left = createTree();
printf("Enter the right child of %d:\n", data);
root->right = createTree();
}
return root;
}
// 先序遍历二叉树
void preorder(struct node *root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// 中序遍历二叉树
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
// 后序遍历二叉树
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
// 查找二叉树中是否存在指定元素
struct node *search(struct node *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);
}
}
// 主函数
int main() {
struct node *root = NULL;
root = createTree();
printf("Preorder traversal of the binary tree:\n");
preorder(root);
printf("\nInorder traversal of the binary tree:\n");
inorder(root);
printf("\nPostorder traversal of the binary tree:\n");
postorder(root);
int data;
printf("\nEnter an element to search in the binary tree:\n");
scanf("%d", &data);
if (search(root, data) == NULL) {
printf("%d not found in the binary tree.\n", data);
} else {
printf("%d found in the binary tree.\n", data);
}
return 0;
}
```
注意:此代码仅为示例,实际应用中可能需要根据具体需求进行修改和优化。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)