爱上算法:每日算法(24-2月3号)

本文介绍了如何在Java中实现平衡二叉树的深度计算以及递归判断其是否平衡的过程,通过后序遍历获取节点高度并检查左右子树高度差是否大于1。
摘要由CSDN通过智能技术生成

🌟坚持每日刷算法,😃将其变为习惯🤛让我们一起坚持吧💪

题目链接:110. 平衡二叉树

分析

首先,明确平衡二叉树条件,一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

那么我们就直接可以求出节点的高度,然后计算高度差,从而判断是否平衡

注意: 要去绝对值之后比较高度差是否大于1哦

逐步解决

  • 求高度差,对于二叉树来说,当然是递归啦,使用后序遍历
public int getDepth(TreeNode root){
        if(root == null) return 0;
        return Math.max(1 + getDepth(root.left), 1 + getDepth(root.right));
    }
  • 递归判断平衡
   if(root==null) return true;
        if(Math.abs((getDepth(root.left) - getDepth(root.right)) )> 1){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);

完整代码

class Solution {
    
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        if(Math.abs((getDepth(root.left) - getDepth(root.right)) )> 1){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    public int getDepth(TreeNode root){
        if(root == null) return 0;
        return Math.max(1 + getDepth(root.left), 1 + getDepth(root.right));
    }
}
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

落雨既然

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

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

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

打赏作者

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

抵扣说明:

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

余额充值