【代码】求二叉树叶子结点的个数、递归方式

编写算法,求二叉树叶子结点的个数


题目分析:

求二叉树的叶子结点,就是求二叉树上左右孩子结点都是空的结点,还记得二叉树的三种遍历方式吗?前序遍历、中序遍历和后序遍历,在递归遍历算法中,无论采取哪种遍历方式,我们只需要添加一个条件就可以求得树的叶子结点啦
判断是否是叶子结点的条件是:

题中我采用的前序遍历,我们看代码吧

建立的二叉树形状:

代码实现:

注:此代码除《Domain.h》里面的算法之外,其余代码皆为二叉树的基本操作内容,若有不明白的地方可参考文章:树的基本操作

BiTree.h:
#pragma once
#include<stdio.h>
#include<stdlib.h>
//结点的结构体
struct  BiTreeNode
{
    char data;             //数据域
    BiTreeNode *LeftChild; //左指针域
    BiTreeNode *RightChild;//右指针域
};
typedef BiTreeNode DataType;
//初始化
void initiate(BiTreeNode **root)
{
    (*root) = (BiTreeNode*)malloc(sizeof(BiTreeNode));
    (*root)->LeftChild = NULL;
    (*root)->RightChild = NULL;
}
//在结点的左孩子结点插入新的数据结点
BiTreeNode *LeftInsert(BiTreeNode *root, char data)
{
    if (root == NULL)
    {
        printf("未找到当前结点,插入失败!\n");
        return NULL;
    }
    BiTreeNode *q = (BiTreeNode*)malloc(sizeof(BiTreeNode));
    q->data = data;
    q->RightChild = NULL;
    q->LeftChild = root->LeftChild;
    root->LeftChild = q;
    return q;
}
//在结点的右孩子结点插入新的数据结点
BiTreeNode *RightInsert(BiTreeNode *root, char data)
{
    if (root == NULL)
    {
        printf("未找到当前结点,插入失败!\n");
        return NULL;
    }
    BiTreeNode *q = (BiTreeNode*)malloc(sizeof(BiTreeNode));
    q->data = data;
    q->LeftChild = NULL;
    q->RightChild = root->RightChild;
    root->RightChild = q;
    return q;
}
//访问数据域
void Visit(char data)
{
    printf("%c  ", data);
}
//二叉树的前序遍历
void PreOrder(BiTreeNode *root)
{
    if (root != NULL)
    {
        Visit(root->data);
        PreOrder(root->LeftChild);
        PreOrder(root->RightChild);
    }
}

Domain.h:
#pragma once
#include"BiTree.h"
/*求二叉树叶子结点个数,采用前序遍历*/
int NumOfLeff(DataType *root)
{
    //采用static,每次进入函数的时候number不会被重新置0
    static int number = 0;
    if (root != NULL)
    {
        /*判断为叶子结点的条件——没有左右孩子结点*/
        if (root->LeftChild == NULL && root->RightChild == NULL)
            number++;
        NumOfLeff(root->LeftChild);
        NumOfLeff(root->RightChild);
    }
    return number;
}
main.c:
#include"Domain.h"
int main()
{
    DataType *root,*p;
    initiate(&root);
    p = root;
    p = LeftInsert(p, 'A');
    p = LeftInsert(p, 'B');
    p = LeftInsert(p, 'D');
    LeftInsert(p, 'H');
    RightInsert(p, 'G');
    p = RightInsert(root->LeftChild , 'C');
    LeftInsert(p, 'E');
    RightInsert(p, 'F');
    //以上为创建一颗二叉树
    printf("前序遍历:\n");
    PreOrder(root->LeftChild);
    //测试叶子结点个数
    printf("\n叶子结点个数:");
    printf("%d  \n", NumOfLeff(root->LeftChild));
    system("pause");
    return 0;
}

有需要非递归解法的小伙伴私信我~


代码编译器:Visual Studio 2017
ok

  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值