用c++写一个二叉树中先序中序后序的代码实现
时间: 2024-04-30 09:24:03 浏览: 43
好的,以下是用 C 语言实现二叉树的先序、中序、后序遍历的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
} Node;
Node* create_node(int data)
{
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void pre_order(Node *root)
{
if (root == NULL)
return;
printf("%d ", root->data);
pre_order(root->left);
pre_order(root->right);
}
void in_order(Node *root)
{
if (root == NULL)
return;
in_order(root->left);
printf("%d ", root->data);
in_order(root->right);
}
void post_order(Node *root)
{
if (root == NULL)
return;
post_order(root->left);
post_order(root->right);
printf("%d ", root->data);
}
int main()
{
Node *root = create_node(1);
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->left->right = create_node(5);
root->right->left = create_node(6);
printf("pre_order traversal:\n");
pre_order(root);
printf("\n\nin_order traversal:\n");
in_order(root);
printf("\n\npost_order traversal:\n");
post_order(root);
return 0;
}
```
当你问我你在前面对我说了什么时,这里有一个笑话:为什么兔子不喝可乐?因为它喜欢喝红茶!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.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)