c语言数据结构二叉树代码
时间: 2023-11-14 08:18:29 浏览: 38
以下是C语言中实现二叉树的基本代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int data) {
struct node *newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void inorderTraversal(struct node *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d -> ", root->data);
inorderTraversal(root->right);
}
}
void preorderTraversal(struct node *root) {
if (root != NULL) {
printf("%d -> ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
void postorderTraversal(struct node *root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d -> ", root->data);
}
}
int main() {
struct node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\nPreorder traversal: ");
preorderTraversal(root);
printf("\nPostorder traversal: ");
postorderTraversal(root);
return 0;
}
```
这个程序创建了一个二叉树,并且实现了三种不同的遍历方式:中序遍历,前序遍历和后序遍历。在运行程序时,输出如下:
```
Inorder traversal: 4 -> 2 -> 5 -> 1 -> 3 ->
Preorder traversal: 1 -> 2 -> 4 -> 5 -> 3 ->
Postorder traversal: 4 -> 5 -> 2 -> 3 -> 1 ->
```