创建二叉树的程序,并设计二叉树的三种遍历,c语言,包含main函数
时间: 2024-11-20 16:39:41 浏览: 50
创建二叉树的程序通常涉及结构体定义节点、插入节点以及遍历操作。这里是一个简单的示例,包括了二叉树的基本结构,以及前序遍历、中序遍历和后序遍历的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 插入节点到二叉树
TreeNode* insert(TreeNode* root, int value) {
if (root == NULL) {
return (TreeNode*)malloc(sizeof(TreeNode));
}
if (value < root->data) {
root->left = insert(root->left, value);
} else {
root->right = insert(root->right, value);
}
return root;
}
// 前序遍历(根-左-右)
void inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
// 中序遍历(左-根-右)
void inorderTraversal2(TreeNode* root) {
if (root != NULL) {
inorderTraversal2(root->left);
printf("%d ", root->data);
inorderTraversal2(root->right);
}
}
// 后序遍历(左-右-根)
void postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}
int main() {
// 初始化一个空的二叉树
TreeNode* root = NULL;
// 插入一些节点示例
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// 打印不同的遍历结果
printf("前序遍历: ");
inorderTraversal(root);
printf("\n");
printf("中序遍历: ");
inorderTraversal2(root);
printf("\n");
printf("后序遍历: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
在这个程序中,我们首先定义了一个`TreeNode`结构来表示二叉树的节点,然后实现了插入节点和三种遍历方式。在`main`函数中,我们构建了一个简单的二叉树并演示了这三种遍历方法。
阅读全文
相关推荐


















