二叉树的创建和遍历C语言数据结构实验报告
时间: 2023-12-12 16:04:07 浏览: 37
好的,下面是一个二叉树的创建和遍历的C语言代码实现,供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体定义
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 创建二叉树
struct Node* createBinaryTree() {
struct Node* root = NULL;
int data;
printf("请输入节点的值(输入-1表示该节点为空):");
scanf("%d", &data);
if (data == -1) {
return NULL;
} else {
root = (struct Node*)malloc(sizeof(struct Node));
root->data = data;
printf("请输入%d的左子节点:\n", data);
root->left = createBinaryTree();
printf("请输入%d的右子节点:\n", data);
root->right = createBinaryTree();
}
return root;
}
// 先序遍历
void preOrder(struct Node* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(struct Node* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
// 后序遍历
void postOrder(struct Node* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
int main() {
struct Node* root = NULL;
root = createBinaryTree();
printf("先序遍历结果:\n");
preOrder(root);
printf("\n中序遍历结果:\n");
inOrder(root);
printf("\n后序遍历结果:\n");
postOrder(root);
return 0;
}
```
这个程序实现了二叉树的创建和三种遍历方式(先序、中序、后序),具体实现方法如下:
- 创建二叉树:通过递归的方式,从根节点开始输入节点的值,如果输入的值为-1,则表示该节点为空,返回NULL;否则,创建一个新的节点,将其值赋为输入的值,然后递归调用该函数,创建左子节点和右子节点,并将它们分别赋值给该节点的左右指针。
- 先序遍历:先输出当前节点的值,然后递归遍历左子树和右子树。
- 中序遍历:先递归遍历左子树,然后输出当前节点的值,最后递归遍历右子树。
- 后序遍历:先递归遍历左子树和右子树,最后输出当前节点的值。
当程序运行时,会提示用户输入每个节点的值,然后输出三种遍历方式的结果。注意,这个程序没有进行内存释放,实际使用时需要注意内存泄漏问题。