我的解题:
1.每个节点都需要重复求高度
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(isBalanced(root->left)&&isBalanced(root->right)
&&abs(func(root->left)-func(root->right))<=1) return true;
else return false;
}
int func(TreeNode* root){
if(!root) return 0;
return max(func(root->left),func(root->right))+1;
}
};
2.
class Solution {
public:
bool flag=true;
bool isBalanced(TreeNode* root) {
func(root);
return flag;
}
int func(TreeNode* root){
if(!root) return 0;
int l=func(root->left);
int r=func(root->right);
if(abs(l-r)>1) flag=false;
return max(l,r)+1;
}
};
咦,这为啥还不如上一种呢?