39_2BalancedBinaryTree(平衡二叉树)

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

import common.TreeNodeCommon;

/**
 * @author LemonLin
 * @Description :BalancedBinaryTree39_2
 * @date 2018/5/13-11:17
 * 基本思路是利用求左右二叉树的深度,来求差值,利用递归思想。
 */
public class BalancedBinaryTree39_2 {
    public boolean IsBalanced_Solution(TreeNodeCommon root) {
        //空树也算平衡二叉树
        if (root == null)
            return true;
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        int diff = left-right;
        if (diff>1||diff<-1)
            return false;
        //左右树都是平衡树才能可以
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
    }

    //求树的深度
    public int TreeDepth(TreeNodeCommon root){
        if (root==null){
            return 0;
        }
        int nleft = TreeDepth(root.left);
        int nright = TreeDepth(root.right);
        return (nleft>nright)?(nleft+1):(nright+1);
    }

    public static void main(String[] args) {
        TreeNodeCommon treeNodeCommon1 = new TreeNodeCommon(10);
        TreeNodeCommon treeNodeCommon2 = new TreeNodeCommon(5);
        TreeNodeCommon treeNodeCommon3 = new TreeNodeCommon(12);
        TreeNodeCommon treeNodeCommon4 = new TreeNodeCommon(4);
        TreeNodeCommon treeNodeCommon5 = new TreeNodeCommon(7);

        treeNodeCommon1.left = treeNodeCommon2;
        treeNodeCommon1.right = treeNodeCommon3;
        treeNodeCommon2.left = treeNodeCommon4;
        treeNodeCommon2.right = treeNodeCommon5;

        BalancedBinaryTree39_2 balancedBinaryTree39_2 = new BalancedBinaryTree39_2();
        boolean b = balancedBinaryTree39_2.IsBalanced_Solution(treeNodeCommon1);
        System.out.println(b);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值