给定先序序列,按照该序列创建对应的二叉树,并输出其先序、中序和后序遍历序列代码c语言
时间: 2023-12-08 13:50:31 浏览: 139
以下是给定先序序列创建二叉树,并输出先序、中序和后序遍历序列的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 根据先序遍历序列创建二叉树
TreeNode* createTree(char* preOrder, int* index) {
if (preOrder[*index] == '\0' || preOrder[*index] == '#') {
(*index)++;
return NULL;
}
TreeNode* root = malloc(sizeof(TreeNode));
root->val = preOrder[(*index)++];
root->left = createTree(preOrder, index);
root->right = createTree(preOrder, index);
return root;
}
// 先序遍历
void preOrder(TreeNode* root) {
if (root == NULL) return;
printf("%c ", root->val);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) return;
inOrder(root->left);
printf("%c ", root->val);
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) return;
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->val);
}
int main() {
char preOrder[] = "ABD##E##C#F##";
int index = 0;
TreeNode* root = createTree(preOrder, &index);
printf("先序遍历结果为:");
preOrder(root);
printf("\n中序遍历结果为:");
inOrder(root);
printf("\n后序遍历结果为:");
postOrder(root);
printf("\n");
return 0;
}
```
输出结果为:
```
先序遍历结果为:A B D E C F
中序遍历结果为:D B E A C F
后序遍历结果为:D E B F C A
```
阅读全文