用c语言
时间: 2024-02-17 21:00:55 浏览: 16
好的,以下是使用 C 语言实现二叉树的建立和四种遍历方式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 先序遍历,根左右
void preorder(struct TreeNode* root) {
if (root == NULL) return;
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
// 中序遍历,左根右
void inorder(struct TreeNode* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
// 后序遍历,左右根
void postorder(struct TreeNode* root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
// 层次遍历
void levelorder(struct TreeNode* root) {
if (root == NULL) return;
struct TreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front != rear) {
struct TreeNode* cur = queue[front++];
printf("%d ", cur->val);
if (cur->left) queue[rear++] = cur->left;
if (cur->right) queue[rear++] = cur->right;
}
}
// 建立二叉树
struct TreeNode* buildTree() {
int val;
scanf("%d", &val);
if (val == -1) return NULL;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = val;
root->left = buildTree();
root->right = buildTree();
return root;
}
int main() {
printf("请输入二叉树的节点值,-1表示空节点:\n");
struct TreeNode* root = buildTree();
printf("先序遍历结果:");
preorder(root);
printf("\n");
printf("中序遍历结果:");
inorder(root);
printf("\n");
printf("后序遍历结果:");
postorder(root);
printf("\n");
printf("层次遍历结果:");
levelorder(root);
printf("\n");
return 0;
}
```
注意:这里输入的二叉树按照先序遍历的方式输入,-1 表示空节点。可以根据需要进行修改。