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 {
private:
bool balanceFlag;
int getTreeDepth(TreeNode *root) {
if (!root || !balanceFlag)
return 0;
int sz1 = getTreeDepth(root->left);
int sz2 = getTreeDepth(root->right);
if (abs(sz1 - sz2) > 1)
balanceFlag = false;
return max(sz1, sz2) + 1;
}
public:
bool isBalanced(TreeNode *root) {
balanceFlag = true;
getTreeDepth(root);
return balanceFlag;
}
};