递归的解法:
非平衡的判定条件:
1.左子树不平衡
2.右子树不平衡
3.左右子树的高度差大于1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root)return true;
if(abs(cnt(root->left)-cnt(root->right))>1)
return false;
else
{
if(isBalanced(root->left)&&isBalanced(root->right))
return true;
return false;
}
}
int cnt(TreeNode *root)
{
if(!root)return 0;
return max(cnt(root->left),cnt(root->right))+1;
}
};