用C语言写一下二叉树的代码
时间: 2024-02-25 14:58:26 浏览: 42
好的,以下是一个简单的二叉树代码示例,用C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct BinaryTree {
TreeNode *root;
} BinaryTree;
TreeNode* createNode(int val) {
TreeNode *newNode = (TreeNode*) malloc(sizeof(TreeNode));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void insert(BinaryTree *tree, int val) {
TreeNode *newNode = createNode(val);
if (tree->root == NULL) {
tree->root = newNode;
return;
}
TreeNode *current = tree->root;
while (1) {
if (val < current->val) {
if (current->left == NULL) {
current->left = newNode;
return;
}
current = current->left;
} else {
if (current->right == NULL) {
current->right = newNode;
return;
}
current = current->right;
}
}
}
void inorderTraversal(TreeNode *node) {
if (node == NULL) {
return;
}
inorderTraversal(node->left);
printf("%d ", node->val);
inorderTraversal(node->right);
}
void preorderTraversal(TreeNode *node) {
if (node == NULL) {
return;
}
printf("%d ", node->val);
preorderTraversal(node->left);
preorderTraversal(node->right);
}
void postorderTraversal(TreeNode *node) {
if (node == NULL) {
return;
}
postorderTraversal(node->left);
postorderTraversal(node->right);
printf("%d ", node->val);
}
int main() {
BinaryTree tree = { NULL };
insert(&tree, 5);
insert(&tree, 3);
insert(&tree, 7);
insert(&tree, 1);
insert(&tree, 4);
insert(&tree, 6);
insert(&tree, 8);
printf("Inorder Traversal: ");
inorderTraversal(tree.root);
printf("\n");
printf("Preorder Traversal: ");
preorderTraversal(tree.root);
printf("\n");
printf("Postorder Traversal: ");
postorderTraversal(tree.root);
printf("\n");
return 0;
}
```
这里定义了一个TreeNode结构体来表示二叉树的节点,其中包含节点的值、左子节点和右子节点。BinaryTree结构体则是二叉树的实现,包含根节点的指针。createNode函数用于创建一个新的节点。insert函数使用二叉搜索树的方式插入节点。中序遍历、前序遍历和后序遍历则使用递归的方式。在主函数中,我们创建一个二叉树并进行遍历。
阅读全文