检验二叉树是否为平衡二叉树,即左右子树深度之差的绝对值<=1
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
首先是我的:
public class judgeBalance {
static boolean isBalan=true;
static Scanner in=new Scanner(System.in);
public static boolean isBalanced(TreeNode root) {
test(root);
return isBalan;
}
public static int test(TreeNode T){
if(isBalan==false)
return -1;//一旦确定不是,以后的递归也就没有意义了,直接return
if(T==null)
return 0;
else if(T.left==null&&T.right==null){//此句其实没有必要,只是个人习惯,
//其实上一句递归就相当于这一句, max(0,0)+1;
return 1;
}
if(Math.abs(test(T.left)-test(T.right))>1){
isBalan=false;
return -1;
}
return Math.max(test(T.left),test(T.right))+1;
}
}
第二种可能更容易想,引入左右子树的深度
public static int Dtest(TreeNode T){
if(!isBalan)
return -1;
int Llen=0;
int Rlen=0;
if(T.left==null)
Llen=0;
else
Llen=Dtest(T.left)+1;
if(T.right==null)
Rlen=0;
else
Rlen=Dtest(T.right)+1;
if(Math.abs(Llen-Rlen)>1){
isBalan=false;
return -1;
}
return Llen>Rlen?Llen:Rlen;
}
但是前两种都没有AC。没理解{2 1 3 }是那个二叉树
下面是第三种AC代码
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
TreeNode left = root.left;
TreeNode right = root.right;
int diff = Math.abs(getHeight(left) - getHeight(right));
if(diff > 1) return false;
return isBalanced(left) && isBalanced(right);
}
public int getHeight(TreeNode root) {
if(root == null) return 0;
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
}