-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。 -
本题涉及到二叉树的建立、根据二叉树的前序和后序重建二叉树,后序遍历二叉树,是二叉树的基本综合题,这个题也是之前学习数据结构一直没碰的题目,一定要重点复习,吃透了。
题目描述:
-
输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。 -
-
输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。 -
-
样例输入:
-
ABC BAC FDXEAG XDEFAG
-
样例输出:
-
BCA XEDGAF
代码如下:
#include <stdio.h>
#include <string.h>
struct node {
node * lc;
node * rc;
char c;
}Tree[50];//使用数组来分配空间,免去malloc
char strPre[30];//保存前序序列
char strIn[30];//保存中序序列
int loc;// 数组元素个数
node * create()
{
node p;
p.lc=p.rc=NULL;
Tree[loc]=p;
return &Tree[loc++];//取地址符号!!
}
node * build(int s1,int e1,int s2,int e2)
{ //s1,e1为前序序列起点终点,s2,e2为后序序列起点终点
//为该结点(S1)分配空间
node * ret = create();
ret->c=strPre[s1];
int pos;
//找到该结点在后序序列中的位置
for(pos=s2;pos<=e2;pos++)
{
if(strIn[pos]==strPre[s1]) break;
}
//存在左子树,递归建立左子树
if(pos!=s2)
{
ret->lc=build(s1+1,s1+(pos-s2),s2,pos-1);
}
//存在右子树,则递归建立右子树
if(pos!=e2)
{
ret->rc=build(s1+(pos-s2)+1,e1,pos+1,e2);
}
return ret;
}
void PostOrder(node * root)
{
if(root->lc!=NULL)
PostOrder(root->lc);
if(root->rc!=NULL)
PostOrder(root->rc);
printf("%c",root->c);
}
int main(int argc, char** argv) {
//注!字符串不需要初始化,直接扫描即可
while(scanf("%s",strPre)!=EOF)
{
scanf("%s",strIn);
loc=0;//初始化变量空间
int Len =strlen(strPre);
node *T=build(0,Len-1,0,Len-1);
PostOrder(T);
printf("\n");
}
return 0;
}