#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *leftChild;
struct node *rightChild;
}BiNode, *BiTree;
void PreOrder(BiTree root) {
if (root) {
printf("%c", root->data);
PreOrder(root->leftChild);
PreOrder(root->rightChild);
}
}
void PostOrder(BiTree root) {
if (root) {
PostOrder(root->leftChild);
PostOrder(root->rightChild);
printf("%c", root->data);
}
}
void CreateBiTreeByPreAndIn(BiTree* root, char* pre, char* in, int n)
{
int flag = 0;
*root = (BiTree)malloc(sizeof(BiNode));
if(n == 0)
{
*root = NULL;
return;
}
(*root)->data = pre[0];
for(int i = 0; i < n; i++)
{
if(in[i] == (*root)->data)
{
flag = i;
break;
}
}
CreateBiTreeByPreAndIn(&((*root)->leftChild), pre+1, in, flag);
CreateBiTreeByPreAndIn(&((*root)->rightChild), pre+1+flag, in+1+flag, n-flag-1);
}
void CreateBiTreeByInAndPost(BiTree *root, char *inStr, char *postStr, int n) {
int cnt = 0;
*root = (BiTree)malloc(sizeof(BiNode));
if (n == 0) {
*root = NULL;
return ;
}
else {
(*root)->data = postStr[n-1];
for (int i = 0; i < n; i++) {
if (inStr[i] == (*root)->data) {
cnt = i;
break;
}
}
CreateBiTreeByInAndPost(&((*root)->leftChild), inStr, postStr, cnt);
CreateBiTreeByInAndPost(&((*root)->rightChild), inStr+cnt+1, postStr+cnt, n-cnt-1);
}
}
int main(void) {
char perStr[50], inStr[50], postStr[50];
BiTree root;
scanf("%s%s", inStr, postStr);
CreateBiTreeByInAndPost(&root, inStr, postStr, strlen(inStr));
PreOrder(root);
return 0;
}
样例一(先序中序)
ABDECFG
DBEACGF
输出
DEBGFCA
样例二(中序后序)
DBEACGF
DEBGFCA
输出
ABDECFG