用C语言写出一个知道了前序和中序求后序的
时间: 2023-08-15 20:30:40 浏览: 86
以下是用C语言实现求解二叉树后序遍历序列的代码,该算法基于前序遍历序列和中序遍历序列构建二叉树,然后通过后序遍历算法输出其后序遍历序列。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
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;
}
TreeNode* buildTree(char* preorder, char* inorder, int inStart, int inEnd) {
static int preIndex = 0;
if (inStart > inEnd) {
return NULL;
}
TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->data = preorder[preIndex++];
newNode->left = NULL;
newNode->right = NULL;
if (inStart == inEnd) {
return newNode;
}
int inIndex = search(inorder, inStart, inEnd, newNode->data);
newNode->left = buildTree(preorder, inorder, inStart, inIndex - 1);
newNode->right = buildTree(preorder, inorder, inIndex + 1, inEnd);
return newNode;
}
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%c ", root->data);
}
int main() {
char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C'};
int len = sizeof(preorder) / sizeof(preorder[0]);
TreeNode* root = buildTree(preorder, inorder, 0, len - 1);
printf("后序遍历序列: ");
postorder(root);
return 0;
}
```
程序输出结果为:
```
后序遍历序列: D E B F C A
```
代码中通过 `buildTree` 函数构建二叉树,该函数通过递归实现,在每次递归中调用 `search` 函数查找中序遍历序列中当前节点在数组中的索引位置,然后递归调用 `buildTree` 函数构建左右子树。最后,程序通过 `postorder` 函数输出二叉树的后序遍历序列。
阅读全文