用c语言编写一段二叉树的三种遍历(先序,中序和后序)
时间: 2023-07-21 20:17:05 浏览: 88
好的,以下是用C语言编写的二叉树的三种遍历(先序,中序和后序)的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 先序遍历
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); // 先访问根节点
preorderTraversal(root->left); // 再访问左子树
preorderTraversal(root->right); // 最后访问右子树
}
// 中序遍历
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left); // 先访问左子树
printf("%d ", root->val); // 再访问根节点
inorderTraversal(root->right); // 最后访问右子树
}
// 后序遍历
void postorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left); // 先访问左子树
postorderTraversal(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 = NULL;
return root;
}
int main() {
struct TreeNode* root = createTree();
printf("先序遍历结果:");
preorderTraversal(root);
printf("\n中序遍历结果:");
inorderTraversal(root);
printf("\n后序遍历结果:");
postorderTraversal(root);
return 0;
}
```
输出结果为:
```
先序遍历结果:1 2 3 4
中序遍历结果:2 1 4 3
后序遍历结果:2 4 3 1
```
阅读全文