用c++编写二叉树的先序遍历,中序遍历,后序遍历
时间: 2024-05-07 14:15:16 浏览: 12
下面是用C语言实现二叉树的先序遍历、中序遍历和后序遍历的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建一个新的节点
TreeNode* createNode(int val) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 向二叉树中插入一个节点
TreeNode* insert(TreeNode *root, int val) {
if (root == NULL) {
return createNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else if (val > root->val) {
root->right = insert(root->right, val);
}
return root;
}
// 先序遍历
void preorder(TreeNode *root) {
if (root != NULL) {
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
}
// 中序遍历
void inorder(TreeNode *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
}
// 后序遍历
void postorder(TreeNode *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
}
int main() {
TreeNode *root = createNode(5);
insert(root, 2);
insert(root, 8);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 9);
printf("先序遍历:");
preorder(root);
printf("\n");
printf("中序遍历:");
inorder(root);
printf("\n");
printf("后序遍历:");
postorder(root);
printf("\n");
return 0;
}
```
以上代码运行结果为:
```
先序遍历:5 2 1 3 8 6 9
中序遍历:1 2 3 5 6 8 9
后序遍历:1 3 2 6 9 8 5
```