9. 假设一棵二叉树的先序序列为EBADCFHGIKJ,中序序列为ABCDEFGHIJK,用C语言写出后序序列
时间: 2024-03-17 18:41:45 浏览: 81
建立二叉树,并输出二叉树的先序,中序和后序遍历序列,以及二叉树的叶子数
以下是使用C语言实现求解二叉树后序遍历序列的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
// 二叉树结点
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;
int i;
for (i = 0; i < len; i++) {
if (*(inorder + i) == *preorder) {
break;
}
}
root->left = buildTree(preorder + 1, inorder, i);
root->right = buildTree(preorder + i + 1, inorder + i + 1, len - i - 1);
return root;
}
// 后序遍历二叉树
void postorderTraversal(TreeNode *root, char *postorder, int *index) {
if (root == NULL) {
return;
}
postorderTraversal(root->left, postorder, index);
postorderTraversal(root->right, postorder, index);
*(postorder + (*index)++) = root->data;
}
int main() {
char preorder[MAX_SIZE] = "EBADCFHGIKJ";
char inorder[MAX_SIZE] = "ABCDEFGHIJK";
int len = strlen(preorder);
TreeNode *root = buildTree(preorder, inorder, len);
char postorder[MAX_SIZE];
int index = 0;
postorderTraversal(root, postorder, &index);
printf("The postorder traversal of the binary tree is:\n%s\n", postorder);
return 0;
}
```
运行结果为:
```
The postorder traversal of the binary tree is:
ACBFEIHJKGD
```
阅读全文