数据结构实验之二叉树的建立与遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
输入
输入一个长度小于50个字符的字符串。
输出
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
示例输入
abc,,de,g,,f,,,
示例输出
cbegdfacgefdba35
提示
来源
ma6174
示例程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int m=0;
typedef struct node
{
char date;
struct node *ltree;
struct node *rtree;
} *dt,tree;
//****************************************//
dt maktree()
{
char a;
dt t=(dt)malloc(sizeof(tree));
scanf("%c",&a);
if(a!=',')//此处只需考虑是否为‘,’因为即使为’\0‘.也和没有录入一样。
{
t->date=a;
t->ltree=maktree();
t->rtree=maktree();
}
else
{
t= NULL;
}
return t;
}
//****************************************//
void zhongchu(dt t)
{
if(t!=NULL)
{
zhongchu(t->ltree);
printf("%c",t->date);
zhongchu(t->rtree);
}
}
void backout(dt t)
{
if(t!=NULL)
{
backout(t->ltree);
backout(t->rtree);
printf("%c",t->date);
}
}
void yezi(dt t)
{
if(t!=NULL)
{
if(t->ltree==NULL&&t->rtree==NULL)
m++;
else
{
yezi(t->ltree);
yezi(t->rtree);
}
}
}
int cen(dt t)
{
int b,d,max;
if(t!=NULL)
{
b=cen(t->ltree);
d=cen(t->rtree);
max=b>d?b:d;
return max+1;
}
else
return 0;
}
int main()
{
dt T;
T=maktree();
zhongchu(T);
printf("\n");
backout(T);
printf("\n");
yezi(T);
printf("%d\n",m);
printf("%d\n",cen(T));
return 0;
}