题目:
代码(首刷看解析 2024年1月30日):
class Solution {
public:
int depth(TreeNode* root) {
if (root == nullptr) return 0;
int leftHeight = depth(root->left);
if (leftHeight == -1) return -1;
int rightHeight = depth(root->right);
if (rightHeight == -1) return -1;
if (abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return 1 + max(leftHeight,rightHeight);
}
}
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return depth(root) == -1 ? false : true;
}
};