二叉树中相关求解

1.二叉树求深度(一般求法)

在递归计算深度时,我们应该将当前节点的左右子树分别递归求解深度,然后取其中较大的值加1即为当前节点所在二叉树的深度。

int GetDepthOfBiTree ( BiTree T)
{
    if (!T) return 0; // 如果节点为空,则深度为0
    int ldepth = GetDepthOfBiTree(T->lchild);// 左子树深度
    int rdepth = GetDepthOfBiTree(T->rchild);// 右子树深度
    return (ldepth > rdepth ? ldepth : rdepth) + 1;// 当前节点为根的二叉树深度为较大值加1
}

 2.二叉树求叶子结点个数

int LeafCount(BiTree T)
{
    int c;
    if (!T) c = 0;//结点为空,叶子结点为0
    else if (!T->lchild && !T->rchild) c = 1;//左右孩子同时为空,则该节点为叶子节点,个数为1;
    else c = LeafCount(T->lchild) + LeafCount(T->rchild);//递归左右数的叶子节点数
    return c;
    
}

3. 求二叉树的分枝结点(非终端结点)个数

//函数原型
int BinTreeNumBranch(const TNODE *root);

//实现代码如下:
int BinTreeNumBranch(const TNODE *root)
{
    if (root == NULL) return 0;
    else return ((root->lch || root->rch) & 1) + BinTreeNumBranch(root->lch) + BinTreeNumBranch(root->rch);
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值