#include <stdio.h>
#include <malloc.h>
typedef struct bnode
...{
char data;
struct bnode *left, *right;
}btree;
btree *creat()
...{
btree *t;
char p;
p = getchar();
if (p == '#')
return NULL;
else
...{
t = (btree *)malloc(sizeof(btree));
t->data = p;
t->left = creat();
t->right = creat();
return t;
}
}
void preorder(btree *t)
...{
if (t != NULL)
...{
printf("%3c", t->data);
preorder(t->left);
preorder(t->right);
}
}
void inorder(btree *t)
...{
if (t != NULL)
...{
inorder(t->left);
printf("%3c", t->data);
inorder(t->right);
}
}
void postorder(btree *t)
...{
if (t != NULL)
...{
postorder(t->left);
postorder(t->right);
printf("%3c", t->data);
}
}
int m = 0;
int leaves(btree *t)
...{
if (t != NULL)
...{
if (t->left == NULL && t->right == NULL)
m++;
else
...{
leaves(t->left);
leaves(t->right);
}
}
return m;
}
int depth(btree *t)
...{
int dep1, dep2;
if (t == NULL)
return 0;
else
...{
dep1 = depth(t->left);
dep2 = depth(t->right);
return (dep1 > dep2 ? dep1 + 1 : dep2 + 1);
}
}
int main()
...{
printf("输入创建二叉树的字符 ");
btree *tree_1 = creat();
printf("先序遍历 ");
preorder(tree_1);
printf(" ");
printf("中序遍历 ");
inorder(tree_1);
printf(" ");
printf("后序遍历 ");
postorder(tree_1);
printf(" ");
int num = leaves(tree_1);
printf("叶节点的个数:%d ", num);
printf("二叉树的深度:%d ", depth(tree_1));
}
本文介绍了一个二叉树的C语言实现,包括创建、先序、中序及后序遍历,并演示了如何计算叶节点数量及二叉树深度。
455

被折叠的 条评论
为什么被折叠?



