Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc, ,de,g, ,f, , , (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Sample Input
abc, ,de,g, ,f, , ,
Sample Output
cbegdfa
cgefdba
题解:
在构造二叉树和中序后序遍历的过程中,递归都是很重要的,当然要完全能明白递归的过程也是不容易的。就比如这道题,给出的序列为先序遍历序列abc,de,g,f, (其中,表示空结点),在递归建树的过程中,首先从第一个字符开始,第一个字符为a,所以root->data=a,进入 root->l=creat()中,在 root->l=creat()中,遍历到了第二个字符b,这时 root->l=creat()函数的root->data=b,即总根的root->l=b,在 root->l=creat()中进行完root->data=b后,又进入root->l=creat(),此时遍历到第三个字符c,因此在root->l=creat()中的root->l=creat()中的root->data=c,对于总的根来说就是root->l->l=c,执行完root->l=creat()中的root->l=creat()中的root->data=c后,又进入root->l=creat(),此时遍历到第四个字符,为“,”这时root->l=creat()中的root->l=creat()中的root->l=creat()中root=NULL,即对于总根来说,root->l->l->l=NULL,可以往回返了,返回到上一层的root->l=creat()执行完的位置,执行下一句 root->r=creat(),这时遍历到第五个字符“,”,说明root->l=creat()中的root->l=creat()中的 root->r=creat()中root=NULL,即对于总根来说,root->l->l->r=NULL,也可以往回返了。到这里root->l=creat()中的root->l=creat()就执行完了,再执行root->l=creat()中的root->r=creat(),此时遍历到第六个字符“d”,因此,对于总根来说,root->l->r=d······就写到这里吧,再递归下去就要晕了,好像是这么个递归的过程。
#include <stdio.h>
#include <stdlib.h>
char a[60];
int c;
struct node
{
char data;
struct node *l,*r;
};
struct node *creat()
{
struct node *root;
if(a[++c]==',')root=NULL;
else
{
root=(struct node*)malloc(sizeof(struct node));
root->data=a[c];
root->l=creat();
root->r=creat();
}
return root;
}
void zhongxu(struct node *root)
{
if(root)
{
zhongxu(root->l);
printf("%c",root->data);
zhongxu(root->r);
}
}
void houxu(struct node *root)
{
if(root)
{
houxu(root->l);
houxu(root->r);
printf("%c",root->data);
}
}
int main()
{
struct node *root;
while(scanf("%s",a)!=EOF)
{
c=-1;
root=creat();
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
}
return 0;
}