就相当于是求左右深度,当左右深度差超过一时设置为false。
c++
class Solution {
private:
bool find=true;
int depth(TreeNode* node){
if(node==NULL){
return 0;
}
int left_height;
int right_height;
left_height=depth(node->left);
right_height=depth(node->right);
if(abs(left_height-right_height)>1){
find=false;
}
return max(left_height,right_height)+1;
}
public:
bool isBalanced(TreeNode* root) {
depth(root);
return find;
}
};