[算法][力扣110]平衡二叉树

给定一个二叉树,判断它是否是 平衡二叉树

分析: 平衡二叉树的任意节点的左右子树高度差(平衡因子)绝对值不超过1

java 复制代码
public boolean isBalanced(TreeNode root) {
        int leftDeep = countDeep(root.left);
        int rightDeep = countDeep(root.right);
        return Math.abs((leftDeep - rightDeep)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

private int countDeep(TreeNode root) {
        // 递归跳出条件
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }

        // 计算左右子树的节点个数
        int leftCount = countDeep(root.left);
        int rightCount = countDeep(root.right);

        // 左右子树节点的和 + 当前节点1
        return Math.max(leftCount, rightCount) + 1;
}
相关推荐
ZhengEnCi16 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David17 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi17 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_61817 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang17 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_9707038319 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你021419 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi20 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Flynn Liang20 小时前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai
liminla!20 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法