在Dev-c++中用c语言写出代码,创建一棵二叉树,对其实现先序、中序、后序遍历
时间: 2024-02-02 12:05:26 浏览: 110
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode *createTree() {
int data;
TreeNode *root = NULL;
printf("请输入节点的值(输入-1结束):");
scanf("%d", &data);
if (data == -1) {
root = NULL;
} else {
root = (TreeNode *) malloc(sizeof(TreeNode));
root->data = data;
root->left = createTree();
root->right = createTree();
}
return root;
}
// 先序遍历
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);
}
int main() {
TreeNode *root = createTree();
printf("先序遍历结果为:");
preOrder(root);
printf("\n中序遍历结果为:");
inOrder(root);
printf("\n后序遍历结果为:");
postOrder(root);
printf("\n");
return 0;
}
```
运行程序后,按照提示输入节点的值,创建一棵二叉树,然后分别输出先序、中序、后序遍历的结果。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)