创建二叉树和实现二叉树的三种遍历 a. 根据提示输入字符型数据创建二叉树,输入值为所有字符型数据 b. 输出为遍历后的每个结点的值的顺序 c. 创建二叉树并能实现二叉树的先序、中序、后序遍历 d. 如果输入数据为:a b c 输出结果为:a b c b a c b c a 程序流程:main()àclrscr()àcreatetree()àpreorder()àinorder()àpostorder
时间: 2023-11-27 12:53:22 浏览: 31
下面是用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode *createTree() {
char ch;
scanf("%c", &ch);
if (ch == '#') {
return NULL;
} else {
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = ch;
root->left = createTree();
root->right = createTree();
return root;
}
}
// 先序遍历
void preorder(TreeNode *root) {
if (root != NULL) {
printf("%c ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// 中序遍历
void inorder(TreeNode *root) {
if (root != NULL) {
inorder(root->left);
printf("%c ", root->data);
inorder(root->right);
}
}
// 后序遍历
void postorder(TreeNode *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%c ", root->data);
}
}
int main() {
printf("请输入字符型数据创建二叉树,输入值为所有字符型数据,#表示空节点:\n");
TreeNode *root = createTree();
printf("先序遍历结果为:");
preorder(root);
printf("\n中序遍历结果为:");
inorder(root);
printf("\n后序遍历结果为:");
postorder(root);
return 0;
}
```
输入样例:
```
请输入字符型数据创建二叉树,输入值为所有字符型数据,#表示空节点:
a
b
#
#
c
#
#
```
输出样例:
```
先序遍历结果为:a b c
中序遍历结果为:b a c
后序遍历结果为:b c a
```