基础版本:
int GetBinaryTreeDepth(BinaryTreeNode* pRoot)
{
if (nullptr == pRoot) return 0;
int leftTreeDepth = pRoot->pLeft != nullptr ? GetBinaryTreeDepth(pRoot->pLeft) : 0;
int rightTreeDepth = pRoot->pRight != nullptr ? GetBinaryTreeDepth(pRoot->pRight) : 0;
return (leftTreeDepth > rightTreeDepth) ? (leftTreeDepth + 1) : (rightTreeDepth + 1);
}
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot)
{
if (NULL == pRoot) return true;
int leftTreeDepth = GetBinaryTreeDepth(pRoot->pRight);
int rightTreeDepth = GetBinaryTreeDepth(pRoot->pRight);
if (leftTreeDepth - rightTreeDepth > 1 || leftTreeDepth - rightTreeDepth < -1) return false;
return IsBalanceBinaryTree(pRoot->pLeft) && IsBalanceBinaryTree(pRoot->pRight);
}
改进版本:
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot, int& depth)
{
if (NULL == pRoot)
{
depth = 0;
return true;
}
int leftTreeDepth = 0;
int rightTreeDepth = 0;
if (!IsBalanceBinaryTree(pRoot->pLeft, leftTreeDepth)) return false;
if (!IsBalanceBinaryTree(pRoot->pRight, rightTreeDepth)) return false;
if (leftTreeDepth - rightTreeDepth > 1 || leftTreeDepth - rightTreeDepth < -1) return false;
depth = 1 + (leftTreeDepth > rightTreeDepth ? leftTreeDepth : rightTreeDepth);
return true;
}
bool IsBalanceBinaryTree(BinaryTreeNode* pRoot)
{
if (nullptr == pRoot) return true;
int depth = 0;
return IsBalanceBinaryTree(pRoot, depth);
}