public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int leftH=maxDepth(root.left);
int rightH=maxDepth(root.right);
return Math.abs(leftH-rightH)<=1
&&isBalanced(root.left)
&&isBalanced(root.right);
}
public int maxDepth(TreeNode root){
if(root==null){
return 0;
}
int leftH=maxDepth(root.left);
int rightH=maxDepth(root.right);
return leftH>rightH?leftH+1:rightH+1;
}
代码优化,使得时间复杂度变为O(n)
复制代码
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return maxDepth(root)>=1;
}
public int maxDepth(TreeNode root){
if(root==null){
return 0;
}
int leftH=maxDepth(root.left);
if(leftH<0){
return -1;
}
int rightH=maxDepth(root.right);
if(rightH<0){
return -1;
}
if(Math.abs(leftH-rightH)<=1){
return leftH>rightH?leftH+1:rightH+1;
}else{
return -1;
}
}
第三种写法
复制代码
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return maxDepth(root)>=1;
}
public int maxDepth(TreeNode root){
if(root==null){
return 0;
}
int leftH=maxDepth(root.left);
// if(leftH<0){
// return -1;
// }
int rightH=maxDepth(root.right);
// if(rightH<0){
// return -1;
// }
if(leftH>=0&&rightH>=0
&&Math.abs(leftH-rightH)<=1){
return Math.max(leftH,rightH)+ 1;
}else{
return -1;
}
}