/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
int dep;
return checkBalance(root,dep);
}
bool checkBalance(TreeNode* Node,int &depth){
if (Node==NULL){
depth=0;//递归到叶子的时候,高度为0
return true;
}
int leftDep,rightDep;
bool leftBalance=checkBalance(Node->left,leftDep);
bool rightBalance=checkBalance(Node->right,rightDep);左子和右子树平衡
depth=max(leftDep,rightDep)+1;
return leftBalance&&rightBalance&&(abs(leftDep-rightDep)<=1);//判断条件:左子和右子分别平衡,且高度相差不超过1
}
};