数据结构 二叉树的 创建 求深度 求节点数 求叶子数 (递归)

各个函数汇总

#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef int Status;

#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef struct BinaryNode
{
    ElemType data;
    struct BinaryNode *Lchild, *Rchild;
}BinaryNode,*BinaryTree;
Status CreateBiTree(BinaryTree &T)//创建二叉树
{
    ElemType e;
    scanf("%d",&e);
    if(!e){T=NULL;return OK;}
    else
    {
        T=(BinaryTree)malloc(sizeof(BinaryNode));
        T->data=e;
        if(!T){exit(OVERFLOW);}
        CreateBiTree(T->Lchild);
        CreateBiTree(T->Rchild);
    }
    return OK;
}
int NodeCount(BinaryTree &T)//求节点数
{
    if(!T){return 0;}
    return 1+NodeCount(T->Lchild)+NodeCount(T->Rchild);
}
int LeafCount(BinaryTree &T)//求叶子数
{
    if(!(T->Lchild)&&!(T->Rchild)){return 1;}
    return LeafCount(T->Lchild)+LeafCount(T->Rchild);
}
int DepthOfBinaryTree(BinaryTree &T)//求深度
{
    if(!T){return 0;}
    if((!T->Lchild)&&(!T->Rchild)){return 1;}//加快在叶子上的递归,叶子越多加快幅度越大,也可以不要这一句
    if(DepthOfBinaryTree(T->Lchild)>=DepthOfBinaryTree(T->Rchild)){return 1+DepthOfBinaryTree(T->Lchild);}
    else{return 1+DepthOfBinaryTree(T->Rchild);}
}
int main()
{
    BinaryTree T;
    CreateBiTree(T);
    printf("%d",LeafCount(T));
    getchar();
    getchar();
    return 0;
}

另:更好看的求深度函数

int DepthOfBinaryTree ( BiTree T)
{
    if(!T){return 0;}
    int depthL=DepthOfBinaryTree(T->Lchild)+1;
    int depthR=DepthOfBinaryTree(T->Rchild)+1;
    if(depthL>=depthR){return depthL;}
    else              {return depthR;} 
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值