二叉树本就是一种递归数据结构,题是要根据给出的二叉树的先序遍历序列和中序遍历序列推出后序遍历序列。
PS:构建二叉树的过程本就是遍历的过程。
两种递归代码。
#include <stdio.h>
#include <string.h>
char F[100],M[100];
// f:先序序列index
// b:中序序列begin
// e:中序序列end
/* int dfs 代码 */
int dfs(int f,int b,int e)
{
int i,j;
for (i=b; i<=e && M[i]!=F[f]; i++);
if (b!=i)
f=dfs(f+1,b,i-1);
if (i!=e)
f=dfs(f+1,i+1,e);
// i==b && i==e i==b==e 即为一个叶点
printf("%c",M[i]);
return f;//读到F最后一个元素的下标
}
int main()
{
while (scanf("%s%s",&F,&M)!=EOF)
{
dfs(0,0,strlen(F)-1);
printf("\n");
}
return 0;
}
/* void 代码*/
// lef : 遍历的左右子树长度
// F : 当前状态先序数组
// M : 当前状态中序数组
void dfs(int len,char* F,char* M) {
int p;
if(len<=0) // 蜕化成一个点的时候
return;
p = strchr(M,F[0]) - M + 1;
dfs(p-1,F+1,M);
dfs(len-p,F+p,M+p);
printf("%c",F[0]);
}
int main() {
int treelen;
while(scanf("%s%s",F,M)!=EOF) {
treelen = strlen(F);
dfs(treelen,F,M);
printf("\n");
}
}