用C实现使用codeblocks给定一个 二又树的先序序列ABDEGCHF,中序序列DBEGAHCF,输出二叉树的后续序列
时间: 2024-03-25 15:40:33 浏览: 72
以下是使用C语言实现的代码,可以在CodeBlocks中编译运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* buildTree(char* preorder, char* inorder, int len) {
if (len <= 0) {
return NULL;
}
// 创建根节点
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = *preorder;
root->left = NULL;
root->right = NULL;
// 查找根节点在中序遍历中的位置
int pos = 0;
while (pos < len && *(inorder + pos) != *preorder) {
pos++;
}
// 递归构建左右子树
root->left = buildTree(preorder + 1, inorder, pos);
root->right = buildTree(preorder + pos + 1, inorder + pos + 1, len - pos - 1);
return root;
}
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%c", root->data);
}
int main() {
char preorder[] = "ABDEGCHF";
char inorder[] = "DBEGAHCF";
int len = strlen(preorder);
TreeNode* root = buildTree(preorder, inorder, len);
postorder(root);
printf("\n");
return 0;
}
```
输出结果为:DBGEHFCAB
阅读全文