创建一个二叉树,先序顺序输入二叉树元素,为空时用#表示,然后先序,中序,后序遍历这颗二叉树的序列。c语言
时间: 2023-08-04 18:25:22 浏览: 47
好的,下面是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node* left;
struct node* right;
}Node, *pNode;
// 创建二叉树
void createTree(pNode* root)
{
char ch;
scanf("%c", &ch);
if (ch == '#')
{
*root = NULL;
}
else
{
*root = (pNode)malloc(sizeof(Node));
(*root)->data = ch;
createTree(&(*root)->left);
createTree(&(*root)->right);
}
}
// 先序遍历
void preOrder(pNode root)
{
if (root != NULL)
{
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
// 中序遍历
void inOrder(pNode root)
{
if (root != NULL)
{
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
}
// 后序遍历
void postOrder(pNode root)
{
if (root != NULL)
{
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
}
int main()
{
pNode root;
printf("请输入二叉树的前序遍历序列:\n");
createTree(&root);
printf("先序遍历序列:");
preOrder(root);
printf("\n中序遍历序列:");
inOrder(root);
printf("\n后序遍历序列:");
postOrder(root);
printf("\n");
return 0;
}
```
这个程序可以先输入二叉树的先序遍历序列,例如:AB#D##C##。其中#代表空节点。然后程序会根据输入创建二叉树,并输出先序,中序和后序遍历的序列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)