c语言创建一棵二叉树,对其实现先序、中序、后序遍历。
时间: 2024-01-31 08:04:31 浏览: 18
以下是C语言实现二叉树及遍历的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建一个二叉树节点
TreeNode* create_node(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 构建二叉树
TreeNode* build_tree() {
TreeNode* 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);
root->right->right = create_node(7);
return root;
}
// 先序遍历
void preorder_traversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorder_traversal(root->left);
preorder_traversal(root->right);
}
// 中序遍历
void inorder_traversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorder_traversal(root->left);
printf("%d ", root->val);
inorder_traversal(root->right);
}
// 后序遍历
void postorder_traversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorder_traversal(root->left);
postorder_traversal(root->right);
printf("%d ", root->val);
}
int main() {
TreeNode* root = build_tree();
printf("Preorder Traversal: ");
preorder_traversal(root);
printf("\nInorder Traversal: ");
inorder_traversal(root);
printf("\nPostorder Traversal: ");
postorder_traversal(root);
return 0;
}
```
输出结果为:
```
Preorder Traversal: 1 2 4 5 3 6 7
Inorder Traversal: 4 2 5 1 6 3 7
Postorder Traversal: 4 5 2 6 7 3 1
```
阅读全文