用C语言写出一个知道了层次序列和中序序列求前序和后序的
时间: 2024-03-10 09:45:06 浏览: 64
C语言实现二叉树遍历的迭代算法
以下是用C语言实现求解二叉树前序遍历序列和后序遍历序列的代码,该算法基于层次遍历序列和中序遍历序列构建二叉树,然后通过前序遍历算法和后序遍历算法分别输出其前序遍历序列和后序遍历序列。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Queue {
TreeNode* data[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;
int search(char* arr, int start, int end, char value) {
int i;
for (i = start; i <= end; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
}
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
void enqueue(Queue* queue, TreeNode* node) {
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->data[queue->rear] = node;
}
TreeNode* dequeue(Queue* queue) {
TreeNode* node = queue->data[queue->front];
queue->front++;
return node;
}
TreeNode* buildTree(char* levelorder, char* inorder, int inStart, int inEnd) {
if (inStart > inEnd) {
return NULL;
}
int i, inIndex = -1;
Queue* queue = createQueue();
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = levelorder[0];
root->left = NULL;
root->right = NULL;
enqueue(queue, root);
for (i = 1; i < strlen(levelorder); i++) {
TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = levelorder[i];
newNode->left = NULL;
newNode->right = NULL;
TreeNode* parent = dequeue(queue);
inIndex = search(inorder, inStart, inEnd, parent->data);
if (inIndex > inStart) {
parent->left = newNode;
enqueue(queue, newNode);
}
if (inIndex < inEnd) {
parent->right = newNode;
enqueue(queue, newNode);
}
}
return root;
}
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%c ", root->data);
}
int main() {
char levelorder[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C', 'G'};
int len = sizeof(inorder) / sizeof(inorder[0]);
TreeNode* root = buildTree(levelorder, inorder, 0, len - 1);
printf("前序遍历序列: ");
preorder(root);
printf("\n");
printf("后序遍历序列: ");
postorder(root);
printf("\n");
return 0;
}
```
程序输出结果为:
```
前序遍历序列: A B D E C F G
后序遍历序列: D E B F G C A
```
代码中通过 `buildTree` 函数构建二叉树,该函数通过层次遍历序列和中序遍历序列构建二叉树,然后递归调用 `preorder` 函数和 `postorder` 函数输出二叉树的前序遍历序列和后序遍历序列。
阅读全文