就是:
给出二叉树的中序和后序
打印先序
思路:
递归分治,找到根节点之后把左右子树分开再递归
设置函数
参数为树分别在序列中的下标位置midL,midR,lterL,lterR,在中序中和在后续中
终止条件:
第一:没有位置,即空
第二:长度唯一,直接打印
求解子树在序列中的下标位置:
第一直接拜访后序最后一个下标根节点的位置
第二在中序中找到这个位置pRoot
左子树在中序之中位置就是[midL,pRoot-1]
左子树长度pRoot-midL;
左子树在后序之中位置就是[lterL,lterL+pRoot-midL-1]
右子树在中序之中的位置就是[pRoot+1,midR]
右子树长度midR-pRoot
右子树在后续之中的位置就是[lterR-(midR-pRoot),lterR-1]
最后直接printf根节点即可
#include<stdio.h>
#include<string.h>
char mid[9],lter[9];
int ml,ll;
void fmal(int midL,int midR,int lterL,int lterR);
int main()
{
scanf("%s",mid);
scanf("%s",lter);
ml=strlen(mid);
ll=strlen(mid);
fmal(0,ml-1,0,ll-1);
return 0;
}
void fmal(int midL,int midR,int lterL,int lterR)
{
if(midL==midR)//二者相等
{
printf("%c",mid[midL]);
return ;
}
//读取根节点
char root=lter[lterR];
//寻找根节点
int pRoot=0;
for(;pRoot<=midR;pRoot++)
{
if(mid[pRoot]==root)
{
break;
}
}
//打印根节点
printf("%c",root);
//递归
if(pRoot!=midL)//左子树不空
{
fmal(midL,pRoot-1,lterL,lterL+pRoot-midL-1);
}
if(pRoot!=midR)
{
fmal(pRoot+1,midR,lterR-(midR-pRoot),lterR-1);
}
return ;
}