二叉树的深度
55.1 求一二叉树的深度
解法一:用递归法遍历树的每一条路径,用一引用变量记录所下的层次数,每次到一个叶节点进行一次比较
解法二:用一个队列进行广度优先遍历,直至叶节点,位置一个全局的层数
解法三:因为单纯是计算树的深度,一棵树某一点的深度,无非是左子树+1或右子树+1
解法一
void TreeDepthCore(const BinaryTreeNode* pRoot,int tempdeep,int& maxDeepth)//diy
{
if (pRoot->m_pLeft==nullptr && pRoot->m_pRight==nullptr)
{
maxDeepth = tempdeep > maxDeepth ? tempdeep : maxDeepth;
return;
}
if (pRoot->m_pLeft != nullptr)
TreeDepthCore(pRoot->m_pLeft, tempdeep + 1, maxDeepth);
if (pRoot->m_pRight != nullptr)
TreeDepthCore(pRoot->m_pRight, tempdeep + 1, maxDeepth);
}
int TreeDepth(const BinaryTreeNode* pRoot)//diy 遍历所有路径
{
if (pRoot == nullptr) return 0;
int deepths = 0;
TreeDepthCore(pRoot,1,deepths);
return deepths;
}
解法二:
int TreeDepth2(const BinaryTreeNode* pRoot)//diy 广度优先
{
if (pRoot == nullptr) return 0;
int deepths = 0;
int layerCnt = 1;
std::queue<const BinaryTreeNode*> mQueue;
mQueue.push(pRoot);
while (mQueue.size()>0)
{
if (layerCnt > 0)
deepths++;
int tempCnt = 0;
while (layerCnt>0)
{
const BinaryTreeNode* pTemp = mQueue.front();
mQueue.pop();
if (pTemp->m_pLeft!=nullptr)
{
tempCnt++;
mQueue.push(pTemp->m_pLeft);
}
if (pTemp->m_pRight!=nullptr)
{
tempCnt++;
mQueue.push(pTemp->m_pRight);
}
layerCnt--;
}
layerCnt = tempCnt;
}
return deepths;
}
解法三:
int TreeDepth1(const BinaryTreeNode* pRoot)//diy
{
if (pRoot == nullptr) return 0;
int left = TreeDepth1(pRoot->m_pLeft);
int right = TreeDepth1(pRoot->m_pRight);
return left > right ? (left+1) : (right+1);
}
55.2平衡二叉树,判断一棵树是否是平衡二叉树,只要任意节点的左右深度差超过1,就不是平衡二叉树
解法一:通过递归遍历任何一个节点的左右子树,如果左右子树高度差大于1,返回-1,否则返回子树的高度
int IsBalanced_Solution3_core(const BinaryTreeNode* pRoot)
{
if (pRoot == nullptr) return 0;
if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) return 1;
int left = IsBalanced_Solution3_core(pRoot->m_pLeft);
int right = IsBalanced_Solution3_core(pRoot->m_pRight);
if (left == -1 || right == -1) return -1;
if (left - right > 1 || right - left > 1) return -1;
return left > right ? left+1 : right+1;
}
bool IsBalanced_Solution3(const BinaryTreeNode* pRoot)
{
if (pRoot == nullptr) return true;
if (IsBalanced_Solution3_core(pRoot) == -1) return false;
else
return true;
}