#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node* lchild, * rchild;
} node;
// 创建二叉树
node* create()
{
node* p;
char ch;
// 读入一个字符
scanf("%c", &ch);
if (ch == '#') {
// 如果是#,说明这个位置上没有节点,返回NULL
p = NULL;
}
else {
// 否则,创建新节点
p = (node*)malloc(sizeof(node));
p->data = ch;// 分别递归创建左右子树
p->lchild = create();
p->rchild = create();
}
return p;
}
// 先序遍历
void preorder(node* p)
{
if (p != NULL) {
printf("%c ", p->data); // 输出当前节点的值
preorder(p->lchild); // 递归遍历左子树
preorder(p->rchild); // 递归遍历右子树
}
}
// 中序遍历
void inorder(node* p)
{
if (p != NULL) {
inorder(p->lchild); // 递归遍历左子树
printf("%c ", p->data); // 输出当前节点的值
inorder(p->rchild); // 递归遍历右子树
}
}
// 后序遍历
void postorder(node* p)
{
if (p != NULL) {
postorder(p->lchild); // 递归遍历左子树
postorder(p->rchild); // 递归遍历右子树
printf("%c ", p->data); // 输出当前节点的值
}
}
// 计算结点个数
int nodecount(node* p)
{
if (p == NULL) {
// 空树,节点数为0
return 0;
}
else {
// 节点数等于左右子树节点数之和再加1
return nodecount(p->lchild) + nodecount(p->rchild) + 1;
}
}
// 计算叶子结点的个数
int leafcount(node* p)
{
if (p == NULL) {// 空树,叶子节点数为0
return 0;
}
else if (p->lchild == NULL && p->rchild == NULL)
{// 如果没有左右子树,则当前节点是叶子节点
return 1;
}
else {
// 否则,叶子节点数等于左右子树的叶子节点数之和
return leafcount(p->lchild) + leafcount(p->rchild);
}
}
// 计算深度
int deep(node* p)
{
if (p == NULL) {
return 0;
}
else {
// 左右子树深度的最大值加上1就是整棵树的深度
int left = deep(p->lchild);
int right = deep(p->rchild);
return (left > right ? left : right) + 1;
}
}
int main()
{
node* p = create(); // 创建二叉树
printf("先序遍历: ");
preorder(p); // 先序遍历
printf("\n中序遍历: ");
inorder(p); // 中序遍历
printf("\n后序遍历: ");
postorder(p); // 后序遍历
printf("\n结点的个数为: %d\n", nodecount(p)); // 计算节点数并输出
printf("叶子结点的个数为: %d\n", leafcount(p)); // 计算叶子节点数并输出
printf("二叉树的深度为: %d\n", deep(p)); // 计算深度并输出
return 0;
}