110. Balanced Binary Tree

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 left and right subtrees of every node differ in height by no more than 1.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * @Auther: match
 * @Date: 2021/2/20 11:06
 * @Description:
 * 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 left and right subtrees of every node differ in height by no more than 1.
 *
 * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
 * https://leetcode-cn.com/problems/balanced-binary-tree/
 */
public class IsBalanced {
    //方法一:自顶向下遍历,类似前序遍历 https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }else{
            return Math.abs(height(root.left) - height(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right);
        }
    }
    //求二叉树树高度的函数,记得模板
    public int height(TreeNode root){
        if(root==null){
            return 0;
        }else{
            return Math.max(height(root.left),height(root.right))+1;
        }
    }

    //方法二:自底向上:类似后序遍历
    public boolean isBalanced2(TreeNode root){
        return h2(root) >=0;
    }

    public int h2(TreeNode root){
        if(root == null){
            return  0;
        }
        int leftHeight = h2(root.left);
        int rightHeight =  h2(root.right);
        if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) >1){//如果不满足,则返回-1,
            return -1;
        }else{
            return Math.max(leftHeight,rightHeight) +1;
        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值