题目描述
根据先序序列和中序遍历序列,建立二叉树。输出这棵二叉树的后序遍历序列。
结点个数<=50
第一行:先序序列
第二行:中序序列
样例输入 Copy
ABDECFG
DBEACGF
样例输出 Copy
DEBGFCA
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node{
char data;
struct Node* Lchild;
struct Node* Rchild;
}BiTNode, *BiTree;
void PreOrder(BiTree root) //先序递归遍历
{
if(root)
{
printf("%c", root->data);
PreOrder(root->Lchild);
PreOrder(root->Rchild);
}
}
void InOrder(BiTree root) //中序递归遍历
{
if(root)
{
InOrder(root->Lchild);
printf("%c", root->data);
InOrder(root->Rchild);
}
}
void PostOrder(BiTree root) //后序递归遍历
{
if(root)
{
PostOrder(root->Lchild);
PostOrder(root->Rchild);
printf("%c", root->data);
}
}
//由先中遍历确定二叉树
void CreateTree(BiTree* root, char* pre, char* mid, int n)
{
int flag = 0;
*root = (BiTree)malloc(sizeof(BiTNode));
if(n == 0)
{
*root = NULL;
return;
}
(*root)->data = pre[0];
for(int i = 0; i < n; i++)
{
if(mid[i] == (*root)->data)
{
flag = i;
break;
}
}
CreateTree(&((*root)->Lchild), pre+1, mid, flag);
CreateTree(&((*root)->Rchild), pre+1+flag, mid+1+flag, n-flag-1);
}
int main()
{
BiTree root;
char pre[100];
char mid[100];
memset(pre, 0, 100);
memset(mid, 0, 100);
gets(pre); //输入
gets(mid);
CreateTree(&root, pre, mid, strlen(mid));
PostOrder(root);
return 0;
}