1 //二叉树的建立与遍历
2 //[问题描述] 建立一棵二叉树,并对其进行遍历(先序、中序、后序),打印输出遍历结果。
3 //[基本要求] 从键盘接受输入(先序),以二叉链表作为存储结构,建立二叉树(以先序来建立)
4 //,并采用递归算法对其进行遍历(先序、中序、后序),将遍历结果打印输出。
5 //[测试数据] ABCффDEфGффFффф(其中ф表示空格字符)
6 //则输出结果为 先序:ABCDEGF 中序:CBEGDFA 后序:CGEFDBA
7
8
9
10
11 #include <stdio.h>
12 #include <stdlib.h>
13
14 // 定义二叉树的结点
15 typedef struct TreeNode {
16 char data; // 数据域,用于存储字符
17 struct TreeNode* left; // 左子树指针
18 struct TreeNode* right; // 右子树指针
19 } TreeNode;
20
21 // 创建一个新的树节点
22 TreeNode* createNode(char data) {
23 TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
24 newNode->data = data;
25 newNode->left = newNode->right = NULL;
26 return newNode;
27 }
28
29 // 通过先序遍历字符串建立二叉树
30 TreeNode* buildTree(const char** str) {
31 // 如果当前字符是空格,则返回NULL,表示空树
32 if (**str == ' ' || **str == '\0') {
33 (*str)++; // 向后移动指针
34 return NULL;
35 }
36
37 // 创建当前节点
38 TreeNode* root = createNode(**str);
39 (*str)++; // 向后移动指针
40
41 // 递归建立左子树
42 root->left = buildTree(str);
43
44 // 递归建立右子树
45 root->right = buildTree(str);
46
47 return root;
48 }
49
50 // 先序遍历:根 -> 左 -> 右
51 void preorderTraversal(TreeNode* root) {
52 if (root == NULL) {
53 return;
54 }
55 printf("%c", root->data); // 先访问根节点
56 preorderTraversal(root->left); // 递归遍历左子树
57 preorderTraversal(root->right); // 递归遍历右子树
58 }
59
60 // 中序遍历:左 -> 根 -> 右
61 void inorderTraversal(TreeNode* root) {
62 if (root == NULL) {
63 return;
64 }
65 inorderTraversal(root->left); // 递归遍历左子树
66 printf("%c", root->data); // 访问根节点
67 inorderTraversal(root->right); // 递归遍历右子树
68 }
69
70 // 后序遍历:左 -> 右 -> 根
71 void postorderTraversal(TreeNode* root) {
72 if (root == NULL) {
73 return;
74 }
75 postorderTraversal(root->left); // 递归遍历左子树
76 postorderTraversal(root->right); // 递归遍历右子树
77 printf("%c", root->data); // 访问根节点
78 }
79
80 // 释放二叉树的内存
81 void freeTree(TreeNode* root) {
82 if (root == NULL) {
83 return;
84 }
85 freeTree(root->left); // 释放左子树
86 freeTree(root->right); // 释放右子树
87 free(root); // 释放当前节点
88 }
89
90 int main() {
91 char input[100];
92 printf("请输入先序遍历字符串('ф'代表空字符,结束符为'\\0'):");
93 fgets(input, sizeof(input), stdin); // 读取输入
94 const char* str = input;
95
96 // 构建二叉树
97 TreeNode* root = buildTree(&str);
98
99 // 输出遍历结果
100 printf("先序遍历:");
101 preorderTraversal(root);
102 printf("\n");
103
104 printf("中序遍历:");
105 inorderTraversal(root);
106 printf("\n");
107
108 printf("后序遍历:");
109 postorderTraversal(root);
110 printf("\n");
111
112 // 释放内存
113 freeTree(root);
114
115 return 0;
116 }