JZ39-平衡二叉树
平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
class Solution2 {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
return depth(root)!=-1;
}
public int depth(TreeNode root){
if(root==null){
return 0;
}
int left = depth(root.left);
if(left==-1){ //如果发现子树不平衡之后就没有必要进行下面的高度的求解了.
return -1;
}
int right = depth(root.right);
if(right==-1){ //如果发现子树不平衡之后就没有必要进行下面的高度的求解了
return -1;
}
if(Math.abs(left - right) > 1){ //左右子树高度大于1,就是-1.主要判别条件
return -1;
}else{
return Math.max(left,right) + 1;
}
}
}
查看2道真题和解析
