二叉树模板的C语言实现
时间: 2023-11-20 07:06:33 浏览: 40
以下是二叉树的基本结构体和函数实现的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
/* 二叉树结构体 */
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
/* 初始化二叉树 */
void init(Node **root) {
*root = NULL;
}
/* 插入节点 */
void insert(Node **root, int data) {
if (*root == NULL) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
*root = newNode;
return;
}
if (data < (*root)->data) {
insert(&((*root)->left), data);
} else {
insert(&((*root)->right), data);
}
}
/* 中序遍历 */
void inorder(Node *root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
/* 测试 */
int main() {
Node *root;
init(&root);
insert(&root, 5);
insert(&root, 3);
insert(&root, 7);
insert(&root, 1);
insert(&root, 9);
inorder(root);
return 0;
}
```
上述代码实现了二叉树的基本操作,包括初始化、插入节点、中序遍历等。你可以根据需要进行修改和扩展。