題目描述
判斷給定的二叉樹是否是平衡的
在這個問題中,定義平衡二叉樹為每個節(jié)點的左右兩個子樹高度差的絕對值不超過1的二叉樹
class Solution {
public:
int height(TreeNode* root)
{
if(root == NULL)
return 0;
return max(height(root->left), height(root->right))+1;
}
bool isBalanced(TreeNode* root)
{
if(root == NULL)
return true;
if(height(root->left)-height(root->right)<=1 && height(root->left)-height(root->right)>=-1
&& isBalanced(root->left) && isBalanced(root->right))
return true;
return false;
}
};