Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
class Solution
{
public:
int maxDepth(TreeNode *root)
{
int nDepth, nLeftDep, nRightDep;
if (root == NULL)//如果根节点为空则返回0
return 0;
if (root->left == NULL&&root->right == NULL)//如果根节点的左右子树都是空则返回1
return 1;
nLeftDep = maxDepth(root->left);
nRightDep = maxDepth(root->right);
nDepth = nLeftDep > nRightDep ? nLeftDep : nRightDep;//比较左右子树返回的最大深度,取较大的
return nDepth + 1;
}
bool isBalanced(TreeNode *root)
{
if (root == NULL)
return true;
int nLeftDepth = 0, nRightDepth = 0;
nLeftDepth = maxDepth(root->left);//计算根节点左子树的深度
nRightDepth = maxDepth(root->right);//计算根节点右子树的深度
if (isBalanced(root->left) && isBalanced(root->right) && (nLeftDepth - nRightDepth >= -1)&&
(nLeftDepth - nRightDepth <= 1))//如果左右子树都是深度平衡并且左右子树的深度差都不大于1则返回true否则返回false
{
return true;
}
else
{
return false;
}
}
};