已知一个二叉树的中序遍历序列和后序遍历序列,求这棵树的前序遍历序列,用C语言实现
时间: 2024-03-07 07:43:11 浏览: 90
用C语言程实现树的遍历(算法)。分出先序,中序,后序
以下是C语言实现已知一个二叉树的中序遍历序列和后序遍历序列,求这棵树的前序遍历序列的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int findIndex(char *arr, int start, int end, char target) {
for (int i = start; i <= end; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
TreeNode *buildTree(char *inorder, char *postorder, int inStart, int inEnd, int postStart, int postEnd) {
if (inStart > inEnd || postStart > postEnd) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->val = postorder[postEnd];
int index = findIndex(inorder, inStart, inEnd, postorder[postEnd]);
root->left = buildTree(inorder, postorder, inStart, index - 1, postStart, postStart + index - inStart - 1);
root->right = buildTree(inorder, postorder, index + 1, inEnd, postStart + index - inStart, postEnd - 1);
return root;
}
void preorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
char inorder[MAX_SIZE], postorder[MAX_SIZE];
scanf("%s %s", inorder, postorder);
int len = strlen(inorder);
TreeNode *root = buildTree(inorder, postorder, 0, len - 1, 0, len - 1);
printf("前序遍历序列为:");
preorderTraversal(root);
return 0;
}
```
阅读全文