树的三种遍历、深度、节点、叶子详细代码

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序老猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值