Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Example Input
abc,,de,g,,f,,,
Example Output
cbegdfa
cgefdba
3
5
Hint
Author
ma6174
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[55];
int top;
struct node
{
int data;
struct node *l, *r;
};
struct node *creat()//建树
{
struct node *root;
top++;
if(a[top] != ',')
{
root = (struct node*) malloc(sizeof(struct node));
root -> data = a[top];
root -> l = creat();
root -> r = creat();
}
else
root = NULL;
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 yezi(struct node *root)
{
if(root == NULL) return 0;
if(root -> l == NULL && root -> r == NULL)
return 1;
else
return yezi(root -> l) + yezi(root -> r);
}
int deep(struct node *root)
{
int d1, d2;
if(root)
{
d1 = deep(root -> l) + 1;
d2 = deep(root -> r) + 1;
return d1 > d2? d1 : d2;
}
return 0;
}
int main()
{
top = -1;//啊啊啊啊啊,掉了这一步浪费了我好长时间!!!
scanf("%s", a);
struct node *root;
root = creat();
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
printf("%d\n", yezi(root));
printf("%d\n", deep(root));
return 0;
}