[LeetCode]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.

思路

首先,理解题目,判断是否为二叉树高度是否平衡的标准是每个节点的左右子树相差不得超过1

其次,理解题目后,很容易想到这是一道典型的递归题目(ps:特别是面试的时候,二叉树和递归联系的特别多,我面试豌豆荚也是考了一个类似的题目)

最后,首先判断根节点的左右子树高度差,相差大于1返回false,相差不大于1则继续递归的测试根节点的左子树和右子树


AC代码


public class BalancedBinaryTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int x) {
            this.val = x;
        }
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        int lh = getHeight(root.left);
        int rh = getHeight(root.right);

        if (Math.abs(lh - rh) > 1) return false;

        return isBalanced(root.left) && isBalanced(root.right);
    }

    public static int getHeight(TreeNode root) {
        if (root == null) return 0;

        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;

    }
}


吐槽

csdn神马时候才能支持markdown语法编辑博客啊,如果到过年还不支持markdown,果断迁移到segmentfault上了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低调小一

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值