Balanced Binary Tree 平衡二叉树的检验

检验二叉树是否为平衡二叉树,即左右子树深度之差的绝对值<=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;
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值