数据结构实验之二叉树的建立与遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
3
5
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int num = 0;
struct tree
{
int data;
struct tree *l, *r;
} *p[55];
int sum, flag;
char s[55];
struct tree *front_creat()
{
struct tree *root;
char c = s[sum++];
if(c == ',') root = NULL;
else
{
root = (struct tree *)malloc(sizeof(struct tree));
root->data = c;
root->l = front_creat();
root->r = front_creat();
}
return root;
}
void midout(struct tree *root) // 中序遍历(左根右)
{
if(root)
{
midout(root->l);
printf("%c", root->data);
midout(root->r);
}
}
void aftout(struct tree *root) // 后序遍历(左右根)
{
if(root)
{
aftout(root->l);
aftout(root->r);
printf("%c", root->data);
}
}
int depth(struct tree *root) // 求深度
{
int x, y;
if(!root) return 0;
else
{
x = depth(root->l);
y = depth(root->r);
return x > y ? x + 1: y + 1;
}
}
int search_leaf(struct tree *root) // 寻找叶子结点
{
if(root)
{
int i = 0, j = 0;
p[j++] = root;
while(i < j)
{
if(p[i])
{
if(p[i]->l == NULL && p[i]->r == NULL)
flag++;
else
{
p[j++] = p[i]->l;
p[j++] = p[i]->r;
}
}
i++;
}
}
return flag;
}
int main()
{
scanf("%s", s);
flag = 0;
sum = 0;
struct tree *root;
root = front_creat();
midout(root);
printf("\n");
aftout(root);
printf("\n");
printf("%d\n", search_leaf(root));
printf("%d\n", depth(root));
return 0;
}