二叉树:度为2的结点个数、叶子结点的个数、结点的个数

84 篇文章 5 订阅
67 篇文章 2 订阅

度数为2的点
思路分析
  • 通过函数的返回值来传递变量,从而获得最终的结果
  • 首先,在当前结点不为空的情况下
    • 判定是否为度数为2的结点
    • 度数 = 左子结点的度数 + 右子结点的度数(采用递归的方式)
    • 全部递归完了,在返回最终的值
伪码
int BinaryTree::CountDegreeTwo( BinaryTreeNode *T ) const{
    int num = 0;
    if(T)
    {
        if(T->GetLChild() && T->GetRChild())
        {
            num = 1;
        }
        num = num + CountDegreeTwo(T->GetLChild()) + CountDegreeTwo(T->GetRChild())}
    return num;
}
  • 上述过程是递归完整个的过程之后的,最终的值已经彼此相互叠加,然后再将最终的值返回
叶子节点的个数
思路分析
  • 通过函数的返回值来传递变量,从而获得最终的结果
  • 首先,在当前结点不为空的情况下
    • 判定是否为叶子结点
      • 叶子节点已经在最底层了,直接返回值
      • 不是叶子节点,最终的结果为两个的左右两个子树的叶子结点之和,然后求和,直接返回值
    • 全部递归完了,在返回最终的值
实现伪码
int BinaryTree::CountDegreeZero( BinaryTreeNode *T ) const {
    int num = 0,numleft = 0,numright = 0;

   // cout<<"正在计数"<<endl;

    if(T) {
        //在判定当前的结点不为空的情况下
        if(!T->GetLChild() && !T->GetRChild()) {
            num = 1}

        //递归往上进行叶子节点的相加
        else {
            numleft = CountDegreeZero(T->GetLChild());
            numright = CountDegreeZero(T->GetRChild());
            num = numleft + numright;           
        }
    }
    return num;

}
  • 类似的题目思路是相同的,都是通过递归来实现的,前提都是该节点不为空的情况下。
结点的个数
思路分析

任意顺序完整的遍历一次,直接返回最终的结果

实现伪码
template<class ElemType>
int BinaryTree<ElemType>::BinaryTreeSize( BinaryTreeNode<ElemType> *T ) const {
    int num = 0,numleft = 0,numright = 0;
    if(T) {
        numleft = BinaryTreeSize(T->GetLChild());
        numright = BinaryTreeSize(T->GetRChild());
        num = numleft + numright + 1;
    }
    return num;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值