创建二叉树,分别按照先序、中序、后序、层次遍历二叉树,并打印结果 C语言完整代码
时间: 2023-07-10 19:03:13 浏览: 89
建二叉树并分别用先先序、中序和后序遍历,然后输出各遍历序列
5星 · 资源好评率100%
以下是用C语言实现二叉树的创建和遍历的完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 先序遍历二叉树
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历二叉树
void inOrder(TreeNode *root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
// 后序遍历二叉树
void postOrder(TreeNode *root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
// 层次遍历二叉树
void levelOrder(TreeNode *root) {
if (root == NULL) {
return;
}
TreeNode *queue[100];
int front = -1, rear = -1;
queue[++rear] = root;
while (front != rear) {
TreeNode *node = queue[++front];
printf("%c ", node->data);
if (node->left != NULL) {
queue[++rear] = node->left;
}
if (node->right != NULL) {
queue[++rear] = node->right;
}
}
}
// 创建二叉树
TreeNode *createTree(char *preOrder, int *preIndex, char *inOrder, int inStart, int inEnd) {
if (inStart > inEnd) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = preOrder[*preIndex];
root->left = root->right = NULL;
(*preIndex)++;
if (inStart == inEnd) {
return root;
}
int inIndex;
for (inIndex = inStart; inIndex <= inEnd; inIndex++) {
if (inOrder[inIndex] == root->data) {
break;
}
}
root->left = createTree(preOrder, preIndex, inOrder, inStart, inIndex - 1);
root->right = createTree(preOrder, preIndex, inOrder, inIndex + 1, inEnd);
return root;
}
int main() {
char preOrder[] = {'A', 'B', 'D', 'E', 'C', 'F', 'G'};
char inOrder[] = {'D', 'B', 'E', 'A', 'F', 'C', 'G'};
int preIndex = 0;
TreeNode *root = createTree(preOrder, &preIndex, inOrder, 0, 6);
printf("先序遍历结果:");
preOrder(root);
printf("\n中序遍历结果:");
inOrder(root);
printf("\n后序遍历结果:");
postOrder(root);
printf("\n层次遍历结果:");
levelOrder(root);
printf("\n");
return 0;
}
```
输出结果为:
```
先序遍历结果:A B D E C F G
中序遍历结果:D B E A F C G
后序遍历结果:D E B F G C A
层次遍历结果:A B C D E F G
```
这里用了递归的方式实现了先序、中序和后序遍历,用了队列实现了层次遍历。同时也实现了根据先序遍历和中序遍历构建二叉树的功能。
阅读全文