用c语言按先序遍历创建二叉树,再得出中序和后序以及层次遍历结果
时间: 2024-02-25 07:54:35 浏览: 84
举例讲解C语言程序中对二叉树数据结构的各种遍历方式
好的,下面是用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表示该节点为NULL
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);
}
void levelorder(TreeNode *root) {
if (root == NULL) {
return;
}
TreeNode *queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode *cur = queue[front++];
printf("%d ", cur->val);
if (cur->left) {
queue[rear++] = cur->left;
}
if (cur->right) {
queue[rear++] = cur->right;
}
}
}
int main() {
printf("请输入二叉树的先序遍历结果,-1表示该节点为NULL:\n");
TreeNode *root = createTree();
printf("先序遍历结果为:");
preorder(root);
printf("\n中序遍历结果为:");
inorder(root);
printf("\n后序遍历结果为:");
postorder(root);
printf("\n层次遍历结果为:");
levelorder(root);
printf("\n");
return 0;
}
```
输入示例:
```
请输入二叉树的先序遍历结果,-1表示该节点为NULL:
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
层次遍历结果为:1 2 3 4 5
```
希望这个程序能够帮助到你!
阅读全文