用c语言代码编写二叉树的先序,中序,后序
时间: 2023-10-28 11:04:24 浏览: 82
二叉树的前序,中序,后序排列C语言程序
二叉树的先序、中序、后序遍历可以使用递归的方式来实现,以下是使用 C 语言代码实现的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 先序遍历二叉树
void preOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); // 先访问根节点
preOrder(root->left); // 再遍历左子树
preOrder(root->right); // 最后遍历右子树
}
// 中序遍历二叉树
void inOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left); // 先遍历左子树
printf("%d ", root->val); // 再访问根节点
inOrder(root->right); // 最后遍历右子树
}
// 后序遍历二叉树
void postOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left); // 先遍历左子树
postOrder(root->right); // 再遍历右子树
printf("%d ", root->val); // 最后访问根节点
}
// 创建二叉树
struct TreeNode* createTree() {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
int main() {
struct TreeNode* root = createTree();
printf("Preorder traversal: ");
preOrder(root);
printf("\nInorder traversal: ");
inOrder(root);
printf("\nPostorder traversal: ");
postOrder(root);
printf("\n");
return 0;
}
```
以上代码创建了一个二叉树并进行了先序、中序、后序遍历,输出结果为:
```
Preorder traversal: 1 2 3 4 5
Inorder traversal: 2 1 4 3 5
Postorder traversal: 2 4 5 3 1
```
阅读全文