110. Balanced Binary Tree
1.返回bool是为了返回判断的结果,判断当前的结点是否平衡
2.depth是为了记录高度
class IsBalanced {
public:
bool isBalanced(TreeNode* root) {
if (root == NULL)
{
return true;
}
int depth = 0;
return isBalancedCore(root, depth);
}
bool isBalancedCore(TreeNode* root, int& depth)
{
if (root == NULL)
{
depth = 0;
return true;
}
int left = 0;
int right = 0;
if (isBalancedCore(root->left, left) && isBalancedCore(root->right, right))
{
if (abs(left - right) <= 1)
{
depth = left > right ? left + 1 : right + 1;
return true;
}
}
return false;
}
};