0
点赞
收藏
分享

微信扫一扫

第十一章 缓存之更新/穿透/雪崩/击穿

他说Python 2024-10-07 阅读 3

文章目录

题目介绍

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

解法

平衡二叉树:任意节点的左子树和右子树的高度之差的绝对值不超过 1

//利用递归方法自顶向下判断以每个节点为根节点的左右子树的最大深度是否大于1
class 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;
        }
    }
}
举报

相关推荐

0 条评论