c语言要求采用二叉链表作为存贮结构,完成二叉树的建立、先序、中序、和后序遍历的操作。
时间: 2023-12-04 13:04:27 浏览: 43
以下是基于二叉链表的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表示该节点为空。