二叉树的深度
二叉树深度的定义:从根节点到叶子节点依次经过的节点形成树的一条路径,最长路径所包含的节点的个数为树的深度,也即二叉树节点的层数。
可将二叉树的节点定义为如下的形式:
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