标签:二叉树
int TreeDepth(BinaryTreeNode* pRoot)
{
if (pRoot == NULL)
return 0;
int nLeft = TreeDepth(pRoot->m_pLeft);
int nRight = TreeDepth(pRoot->m_pRight);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
解法一:
bool IsBalanced(BinaryTreeNode* pRoot)
{
if (pRoot == NULL)
return true;
int left = TreeDepth(pRoot->m_pLeft);
int right = TreeDepth(pRoot->m_pRight);
int diff = left - right;
if (diff > 1 || diff < -1)
return false;
return IsBalanced(pRoot->m_pLeft) && IsBalanced(pRoot->m_pRight);
}
解法二:
一边遍历一边判断每个结点是不是平衡的。
bool IsBalanced(BinaryTreeNode* pRoot, int* pDepth)
{
if (pRoot == NULL)
{
*pDepth = 0;
return true;
}
int left, right;
if (IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right))
{
int diff = left - right;
if (diff <= 1 && diff >= -1)
{
*pDepth = 1 + (left > right ? left : right);
return true;
}
}
return false;
}
我们只需要给上面的函数传入二叉树的根节点及一个表示结点深度的整型变量即可:
bool IsBalanced(BinaryTreeNode* pRoot)
{
int depth = 0;
return IsBalanced(pRoot, &depth);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:二叉树
原文地址:http://blog.csdn.net/wangfengfan1/article/details/46834329