寫這篇主要因爲這題概括了我現在學到的二叉樹的大部分知識點,所以每一個都用函數標識了。
#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("\n");
print_later(root);//後序輸出
printf("\n");
print_Sequence(root);//樹的層序遍歷
printf("%d\n", leaves(root));//葉子的數量
printf("%d\n", depth_tree(root));//樹的深度
return 0;
}