c语言实现通过二叉树的先序序列和中序序列构建二叉树,然后在main函数中输入二叉树的先序序列为ABDGCEF,中序遍历序列为DGBAECF,并通过后序遍历算法输出二叉树的后序序列GDBEFCA
时间: 2023-10-29 08:10:26 浏览: 119
c代码-递归创建二叉树,先序、中序、后序递归遍历二叉树
5星 · 资源好评率100%
下面是具体的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 在中序序列中查找根节点的位置
int findRoot(char *inOrder, int inStart, int inEnd, char rootVal) {
for (int i = inStart; i <= inEnd; i++) {
if (inOrder[i] == rootVal) {
return i;
}
}
return -1;
}
// 根据先序和中序序列构建二叉树
TreeNode* buildTree(char *preOrder, char *inOrder, int inStart, int inEnd) {
static int preIndex = 0; // 静态变量记录先序序列的下标
if (inStart > inEnd) {
return NULL;
}
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = preOrder[preIndex++];
int rootIndex = findRoot(inOrder, inStart, inEnd, root->data); // 查找根节点在中序序列中的位置
root->left = buildTree(preOrder, inOrder, inStart, rootIndex - 1);
root->right = buildTree(preOrder, inOrder, rootIndex + 1, inEnd);
return root;
}
// 后序遍历二叉树
void postOrder(TreeNode *root) {
if (root) {
postOrder(root->left);
postOrder(root->right);
printf("%c", root->data);
}
}
int main() {
char preOrder[] = "ABDGCEF"; // 先序序列
char inOrder[] = "DGBAECF"; // 中序序列
int len = sizeof(preOrder) / sizeof(preOrder[0]);
TreeNode *root = buildTree(preOrder, inOrder, 0, len - 1);
printf("后序遍历序列为:");
postOrder(root);
return 0;
}
```
运行结果为:
```
后序遍历序列为:GDBEFCA
```
阅读全文