用C语言构造一个二叉树,并遍历二叉树
时间: 2024-01-01 16:18:45 浏览: 60
好的,下面是用C语言构造一个二叉树的代码示例,同时包含了二叉树的前序、中序和后序遍历函数:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 构造二叉树函数
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) { // 输入-1表示该节点为空
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
// 前序遍历函数
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
// 中序遍历函数
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
// 后序遍历函数
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
int main() {
printf("请输入二叉树的节点值,-1表示空节点:\n");
TreeNode* root = createTree();
printf("前序遍历结果:");
preorder(root);
printf("\n中序遍历结果:");
inorder(root);
printf("\n后序遍历结果:");
postorder(root);
printf("\n");
return 0;
}
```
示例输入:
```
请输入二叉树的节点值,-1表示空节点:
1
2
-1
-1
3
4
-1
-1
5
-1
-1
```
示例输出:
```
前序遍历结果:1 2 3 4 5
中序遍历结果:2 1 4 3 5
后序遍历结果:2 4 5 3 1
```
希望这个例子对你有所帮助!