用C++语言编写一个程序,先建立一个二叉树,然后使用递归算法分别在前序、无序、后序遍历二叉树。 注意:程序的输出是三个不同遍历序列的结果。
时间: 2024-05-16 16:12:21 浏览: 7
以下是用C语言编写的程序,实现二叉树的建立和三种遍历方式:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 前序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = NULL;
int data;
scanf("%d", &data);
if (data == -1) { // -1表示该节点为空
return NULL;
} else {
root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
root->left = createTree();
root->right = createTree();
}
return root;
}
int main() {
TreeNode* root = NULL;
printf("请输入二叉树节点数据(-1表示空节点):\n");
root = createTree();
printf("前序遍历结果:");
preOrder(root);
printf("\n");
printf("中序遍历结果:");
inOrder(root);
printf("\n");
printf("后序遍历结果:");
postOrder(root);
printf("\n");
return 0;
}
```
程序的运行结果如下:
```
请输入二叉树节点数据(-1表示空节点):
1 2 -1 -1 3 4 -1 -1 5 -1 -1
前序遍历结果:1 2 3 4 5
中序遍历结果:2 1 4 3 5
后序遍历结果:2 4 5 3 1
```
以上程序中,输入的数据是按照二叉树的前序遍历顺序输入的,-1表示空节点。程序先根据输入的数据创建二叉树,然后分别使用前序、中序、后序遍历三种方式输出遍历结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)