给定一个二叉树,判断它是否是高度平衡的二叉树。Java分治法实现

/**
 * 判断一个二叉树是否为平衡二叉树
 */
public class BalanceTree {

    public static boolean isBalanced(BinaryTree root){

        //如果是平衡树就直接返回大于等于0的高度值,否则就返回-1
        if(getDepth(root) == -1){
            return false;
        }
        return true;

    }

    /**
     * 返回二叉树的高度,这里如果是平衡树就直接返回大于等于0的高度值,否则就返回-1
     * @param root 二叉树
     * @return
     */
    public static int getDepth(BinaryTree root){
        if(root == null){
            return 0;
        }
        //左子树高度
        int left = getDepth(root.left);
        //右子树高度
        int right = getDepth(root.right);
        //这里的-1代表左右子树之间高度差大于1
        if(left == -1 || right == -1 || left - right > 1 || right - left > 1 ){
            return -1;
        }else{
            return Math.max(left, right) + 1;
        }
    }

    public static void main(String[] args){
        BinaryTree head  = new BinaryTree(1);
        BinaryTree left  = new BinaryTree(2);
        BinaryTree right  = new BinaryTree(3);
        BinaryTree left01  = new BinaryTree(4);
        BinaryTree right01  = new BinaryTree(5);
//        BinaryTree right02  = new BinaryTree(6);
        head.left = left;
        head.right = right;
        left.left = left01;
        left.right = right01;
//        left01.right = right02;

        System.out.println(isBalanced(head));
        //返回true 去掉上面的两行注释返回false

    }

}


//二叉树的类
class BinaryTree{
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value){
        left = null;
        right = null;
        this.value = value;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值