递归一直是弱项
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return deepth(pRoot) != -1;
}
private:
int deepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
int ldep = deepth(root->left);
if (ldep == -1) {
return -1;
}
int rdep = deepth(root->right);
if (rdep == -1) {
return -1;
}
int sub = std::abs(ldep - rdep);
// -1会一直向上传递
if (sub > 1) {
return -1;
}
return std::max(ldep, rdep) + 1;
}
};