
解法一
class Solution {
public:
bool isBalanced(TreeNode* root) {
return deepth(root)!=-1;
}
int deepth(TreeNode* root){
if(root==NULL) return 0;
int left=deepth(root->left);
if(left==-1) return -1;
int right=deepth(root->right);
if(right==-1) return -1;
return (abs(left-right)<2)? max(left,right)+1:-1;
}
};
解法二
class Solution {
public:
bool res=true;
bool isBalanced(TreeNode* root) {
dfs(root);
return res;
}
int dfs(TreeNode* root){
if(root==NULL) return 0;
int left=dfs(root->left), right=dfs(root->right);
if(abs(left-right)>1) res=false;
return max(left,right)+1;
}
};