- 题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
- 输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
- 输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
由二叉树的前序遍历序列与中序遍历序列确定后序遍历,这是由于二叉树的前序遍历序列与中序遍历序列可以确定唯一的二叉树,通常的做法是建树,之后进行后序遍历;但在这里不用建树,而是通过模拟后序遍历得出二叉树的后序遍历序列。
#include<stdio.h>
#include<string.h>
char pre[27];
char in[27];
int pos[27];
int ind;
void postorder(char str[],int begin,int end)
{
int k=pos[ind];
if(begin==end)
{
ind++;
printf("%c",str[begin]);
}
else if(begin<end)
{
ind++;
postorder(str,begin,k-1);
postorder(str,k+1,end);
printf("%c",str[k]);
}
}
int main()
{
while(scanf("%s",pre)!=EOF)
{
scanf("%s",in);
int len=strlen(pre);
for(int i=0;i<len;i++)
for(int j=0;j<len;j++)
if(pre[i]==in[j])
pos[i]=j;
ind=0;
postorder(in,0,len-1);
printf("\n");
}
return 0;
}