自顶向下的递归
cpp
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root)
return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
return true;
}
int maxDepth(TreeNode* root){
if(root)
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
return 0;
}
};
自底向上的递归
cpp
class Solution {
public:
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
int height(TreeNode* root){
if(root == NULL)
return 0;
int l = height(root->left);
int r = height(root->right);
if( l == -1 || r == -1 || abs(l - r) > 1)
return -1;
return max(l,r) + 1;
}
};