用C语言编写一个遍历二叉树
时间: 2023-07-18 15:32:32 浏览: 83
C语言实现二叉树遍历
4星 · 用户满意度95%
好的,以下是一个用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) {
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
// 中序遍历二叉树
void inorderTraversal(struct TreeNode* root) {
if (root) {
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
}
// 后序遍历二叉树
void postorderTraversal(struct TreeNode* root) {
if (root) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
}
int main() {
// 构造一个二叉树
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;
// 依次遍历二叉树
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
printf("Postorder Traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
这里定义了一个二叉树的结构体 `TreeNode`,包含节点值 `val`,左子节点 `left` 和右子节点 `right`。然后定义了三个遍历二叉树的函数:先序遍历 `preorderTraversal`,中序遍历 `inorderTraversal` 和后序遍历 `postorderTraversal`。在 `main` 函数中,构造了一个二叉树,并依次遍历该二叉树。
阅读全文