class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
int left = depth(root->left);
int right = depth(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
int depth(TreeNode* root) {
if (!root) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
bool balanced = true;
height(root, balanced);
return balanced;
}
int height(TreeNode* root, bool& balanced) {
if (!root) return 0;
int left = height(root->left, balanced);
int right = height(root->right, balanced);
if (abs(left - right) > 1) {
balanced = false;
return -1;
}
return max(left, right) + 1;
}
};