用c语言写一个程序,已知一棵颗二叉树的后序和中序,创建这棵二叉树,并输出先序遍历的顺序
时间: 2023-05-22 22:04:49 浏览: 92
好的,以下是用C语言实现该程序的代码:
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点
typedef struct node {
char data;
struct node *left, *right;
} TreeNode;
// 查找指定字符在中序序列中的位置
int findPosition(char *inorder, char c) {
int i = 0;
while (inorder[i] != '\0') {
if (inorder[i] == c) {
return i;
}
i++;
}
return -1;
}
// 递归创建二叉树
TreeNode* build(char *inorder, char *postorder, int inStart, int inEnd, int *postIndex) {
// 边界条件
if (inStart > inEnd) {
return NULL;
}
// 获取当前根节点,创建新节点
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = postorder[*postIndex];
node->left = NULL;
node->right = NULL;
(*postIndex)--;
// 递归创建右子树
int inIndex = findPosition(inorder, node->data);
node->right = build(inorder, postorder, inIndex + 1, inEnd, postIndex);
// 递归创建左子树
node->left = build(inorder, postorder, inStart, inIndex - 1, postIndex);
return node;
}
// 先序遍历
void preOrder(TreeNode *node) {
if (node == NULL) {
return;
}
printf("%c ", node->data);
preOrder(node->left);
preOrder(node->right);
}
int main() {
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C', '\0'};
char postorder[] = {'D', 'E', 'B', 'F', 'C', 'A', '\0'};
int postIndex = 5;
// 创建二叉树
TreeNode *root = build(inorder, postorder, 0, 6, &postIndex);
// 输出先序遍历结果
printf("先序遍历结果:");
preOrder(root);
printf("\n");
return 0;
}
阅读全文