求二叉树的深度和宽度

二叉树的深度

二叉树深度的定义:从根节点到叶子节点依次经过的节点形成树的一条路径,最长路径所包含的节点的个数为树的深度,也即二叉树节点的层数。

可将二叉树的节点定义为如下的形式:

struct BinTreeNode{
    int  value;
    BinTreeNode* pLeft;
    BinTreeNode* pRight;
};

解题思路:很自然的可以想到,树的深度等于根节点的左右子树的深度较大值加1,再次很自然的会想到改造二叉树后序遍历的递归方法来实现,代码实现如下:

int treeDepth(BinTreeNode* root){
    if(root==NULL){
        return 0;
    }
    int nLeft=treeDepth(root->m_pLeft);
    int nRight=treeDepth(root->m_pRight);
    return nLeft>nRight?nLeft+1:nRight+1;
}

 

二叉树的宽度

二叉树宽度的定义:含有节点数最多的层中包含的节点数。

解题思路:使用二叉树的层次遍历方法,在层次遍历的过程中,通过读取队列中保留的上一层节点数来记录每层的节点数,以获取所有层中最大的节点数。

实现代码如下:

int treeWidth(BinTreeNode *pRoot){
    if(pRoot == NULL) return 0;

    int lastLevelWidth = 0;
    int CurLevelWidth = 0;
    
    queue<BinTreeNode*> myqueue;  
    myqueue.push(pRoot);    //将根节点入队列  
    int Width = 1;        //二叉树的宽度  
    lastLevelWidth = 1;      
    BinTreeNode *pCur = NULL; 

    while(!myqueue.empty())
    {
    
         while(lastLevelWidth != 0){
         pCur  = myqueue.front();
         myqueue.pop();

         if(pCur->pLeft) myqueue.push(pCur->pLeft);
         if(pCur->pRight) myqueue.push(pCur->pRight);
         lastLevelWidth--;
      }
      CurLevelWidth = myqueue.size();
      Width = CurLevelWidth > Width ? CurLevelWidth : Width ;
      lastLevelWidth = CurLevelWidth ;
         
    }
    return Width; 
  
}

参考文献:https://blog.youkuaiyun.com/K346K346/article/details/51076268

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值