请用C语言实现数据结构中的树
时间: 2023-05-12 14:02:59 浏览: 55
好的,以下是一个简单的C语言实现二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* create_node(int data) {
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert(struct node** root, int data) {
if (*root == NULL) {
*root = create_node(data);
return;
}
if (data < (*root)->data) {
insert(&((*root)->left), data);
} else {
insert(&((*root)->right), data);
}
}
void inorder_traversal(struct node* root) {
if (root == NULL) {
return;
}
inorder_traversal(root->left);
printf("%d ", root->data);
inorder_traversal(root->right);
}
int main() {
struct node* root = NULL;
insert(&root, 50);
insert(&root, 30);
insert(&root, 20);
insert(&root, 40);
insert(&root, 70);
insert(&root, 60);
insert(&root, 80);
inorder_traversal(root);
return 0;
}
```
这段代码实现了二叉树的创建、插入和中序遍历。