自顶向下的递归
类似于二叉树前序遍历
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
return max(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
} else {
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
自底向上的递归
类似于二叉树后序遍历
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
};
class Solution {
private:
bool ans=true;
public:
bool isBalanced(TreeNode* root) {
depth(root);
return ans;
}
int depth(TreeNode* root)
{
if(!root)
return 0;
int left=1+depth(root->left);
int right=1+depth(root->right);
if(abs(left-right)>1)
ans=false;
return max(left,right);
}
};