输出一组数据,建立一个以二叉链表形式存储的二叉树。对所建立的二叉树分别进行先序、中序和后序遍历
时间: 2023-07-22 18:36:54 浏览: 87
好的,下面是一个示例二叉树和对应遍历结果的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int value;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 构建二叉树,返回根节点
TreeNode* buildTree() {
// 创建二叉树节点
TreeNode* A = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* B = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* C = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* D = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* E = (TreeNode*)malloc(sizeof(TreeNode));
// 给节点赋值
A->value = 1;
B->value = 2;
C->value = 3;
D->value = 4;
E->value = 5;
// 构建二叉树
A->left = B;
A->right = C;
B->left = D;
B->right = E;
C->left = NULL;
C->right = NULL;
D->left = NULL;
D->right = NULL;
E->left = NULL;
E->right = NULL;
// 返回根节点
return A;
}
// 先序遍历
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->value);
preorder(root->left);
preorder(root->right);
}
// 中序遍历
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->value);
inorder(root->right);
}
// 后序遍历
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->value);
}
int main() {
// 构建二叉树
TreeNode* root = buildTree();
// 输出遍历结果
printf("先序遍历结果:");
preorder(root);
printf("\n");
printf("中序遍历结果:");
inorder(root);
printf("\n");
printf("后序遍历结果:");
postorder(root);
printf("\n");
return 0;
}
```
输出结果为:
```
先序遍历结果:1 2 4 5 3
中序遍历结果:4 2 5 1 3
后序遍历结果:4 5 2 3 1
```
这里构建的二叉树如下所示:
```
1
/ \
2 3
/ \
4 5
```
阅读全文