写这篇主要因为这题概括了我现在学到的二叉树的大部分知识点,所以每一个都用函数标识了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max(a, b) ((a > b) ? (a) : (b))
char a[55];
int i;
struct tree
{
int data;
struct tree *ltree, *rtree;//建立左子树和右子树,这个完全看个人喜好。男左女右都可以
};
struct tree *creat()//建树
{
struct tree *root;
if(a[i] == ',')
{
i++;
return NULL;
}
else
{
root = (struct tree *)malloc(sizeof(struct tree));
root->data = a[i++];
root->ltree = creat();
root->rtree = creat();
}
return root;
}
void print_mid(struct tree *root)//中序输出
{
if(root == NULL)
return;
else
{
print_mid(root->ltree);
printf("%c", root->data);
print_mid(root->rtree);
}
}
void print_later(struct tree *root)//后序输出
{
if(root == NULL)
return;
else
{
print_later(root->ltree);
print_later(root->rtree);
printf("%c", root->data);
}
}
int leaves(struct tree *root)//数叶子数
{
if(root == NULL)
return 0;
else if(root->ltree == NULL && root->rtree == NULL)
return 1;
else
return leaves(root->ltree) + leaves(root->rtree);
}
int depth_tree(struct tree *root)//计算树的深度
{
int depth = 0;
if(root)
{
int ldepth = depth_tree(root->ltree);
int rdepth = depth_tree(root->rtree);
depth = max(ldepth+1, rdepth+1);
}
return depth;
}
void print_Sequence(struct tree *root)//树的层序遍历
{
struct tree *flag[55];
int head = 0, tail = 0;
flag[tail++] = root;
while(head < tail)
{
if(flag[head])
{
printf("%c", flag[head]->data);
flag[tail++] = flag[head]->ltree;
flag[tail++] = flag[head]->rtree;
}
head++;
}
}
int main()
{
scanf("%s", a);
i = 0;
struct tree *root;
root = (struct tree *)malloc(sizeof(struct tree));
root = creat();
print_mid(root);//中序输出
printf("
");
print_later(root);//后序输出
printf("
");
print_Sequence(root);//树的层序遍历
printf("%d
", leaves(root));//叶子的数量
printf("%d
", depth_tree(root));//树的深度
return 0;
}