剑指 Offer-平衡二叉树

截止到目前我已经写了 500多道算法题,其中部分已经整理成了pdf文档,目前总共有1000多页(并且还会不断的增加),大家可以免费下载
下载链接https://pan.baidu.com/s/1hjwK0ZeRxYGB8lIkbKuQgQ
提取码:6666

在这里插入图片描述
在这里插入图片描述

//计算树中节点的高度
public int depth(TreeNode root) {
    if (root == null)
        return 0;
    return Math.max(depth(root.left), depth(root.right)) + 1;
}

所以这题的代码我们也很容易写出来

public boolean isBalanced(TreeNode root) {
    if (root == null)
        return true;
    //分别计算左子树和右子树的高度
    int left = depth(root.left);
    int right = depth(root.right);
    //这两个子树的高度不能超过1
    return Math.abs(left - right) <= 1;
}

//计算树中节点的高度
public int depth(TreeNode root) {
    if (root == null)
        return 0;
    return Math.max(depth(root.left), depth(root.right)) + 1;
}

在这里插入图片描述
在这里插入图片描述
视频链接

再来看下代码

public boolean isBalanced(TreeNode root) {
    if (root == null)
        return true;
    //分别计算左子树和右子树的高度
    int left = depth(root.left);
    int right = depth(root.right);
    //这两个子树的高度不能超过1,并且他的两个子树也必须是平衡二叉树
    return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}

//计算树中节点的高度
public int depth(TreeNode root) {
    if (root == null)
        return 0;
    return Math.max(depth(root.left), depth(root.right)) + 1;
}

在这里插入图片描述
在这里插入图片描述
视频链接

先判断两个子树是否是平衡的,然后再判断以当前节点为根节点的子树是否是平衡的……。来看下代码

//如果等于-1就表示不是平衡的
private static final int UNBALANCED = -1;

public boolean isBalanced(TreeNode root) {
    return helper(root) != UNBALANCED;
}

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

    //如果左子节点不是平衡二叉树,直接返回UNBALANCED
    int left = helper(root.left);
    if (left == UNBALANCED)
        return UNBALANCED;

    //如果右子节点不是平衡二叉树,直接返回UNBALANCED
    int right = helper(root.right);
    if (right == UNBALANCED)
        return UNBALANCED;

    //如果左右子节点都是平衡二叉树,但他们的高度相差大于1,
    //直接返回UNBALANCED
    if (Math.abs(left - right) > 1)
        return UNBALANCED;

    //否则就返回二叉树中节点的最大高度
    return Math.max(left, right) + 1;
}

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

数据结构和算法

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值