以c语言为基础帮我写一个能够实现各种遍历的二叉树代码
时间: 2023-11-24 18:07:12 浏览: 30
好的,以下是一个实现二叉树遍历的 C 语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct binary_tree {
int data;
struct binary_tree *left;
struct binary_tree *right;
};
// 插入节点
struct binary_tree *insert(struct binary_tree *node, int data) {
if (node == NULL) {
struct binary_tree *temp;
temp = (struct binary_tree *)malloc(sizeof(struct binary_tree));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if (data > (node->data)) {
node->right = insert(node->right, data);
} else if (data < (node->data)) {
node->left = insert(node->left, data);
}
return node;
}
// 先序遍历
void pre_order_traversal(struct binary_tree *node) {
if (node) {
printf("%d ", node->data);
pre_order_traversal(node->left);
pre_order_traversal(node->right);
}
}
// 中序遍历
void in_order_traversal(struct binary_tree *node) {
if (node) {
in_order_traversal(node->left);
printf("%d ", node->data);
in_order_traversal(node->right);
}
}
// 后序遍历
void post_order_traversal(struct binary_tree *node) {
if (node) {
post_order_traversal(node->left);
post_order_traversal(node->right);
printf("%d ", node->data);
}
}
int main() {
struct binary_tree *root = NULL;
root = insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
insert(root, 7);
printf("Pre Order Traversal: ");
pre_order_traversal(root);
printf("\n");
printf("In Order Traversal: ");
in_order_traversal(root);
printf("\n");
printf("Post Order Traversal: ");
post_order_traversal(root);
printf("\n");
return 0;
}
```
注:以上代码实现了二叉树的插入和三种遍历方式(先序遍历、中序遍历、后序遍历),你可以根据你的实际需求进行修改。