LeetCode110 平衡二叉树

  1. 题目

    java 复制代码
    给定一个二叉树,判断它是否是 平衡二叉树
  2. 示例

    java 复制代码
    示例 1:
    输入:root = [3,9,20,null,null,15,7]
    输出:true
    
    示例 2:
    输入:root = [1,2,2,3,3,null,null,4,4]
    输出:false
    
    示例 3:
    输入:root = []
    输出:true
  3. 解题思路

    1. 平衡二叉树 是指该树所有节点的左右子树的深度相差不超过 1。
    2. 方法一:根据平衡二叉树的概念,递归每一个节点其左右子树的深度,判断是否平衡。
    3. 方法二:方法一的优化,减少递归次数。当遇到不是平衡二叉树的节点直接返回,不在继续递归。
  4. 代码(Java)

    java 复制代码
    // 方法一
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if (root == null) {
                return true;
            }
            if (root.left == null && root.right == null) {
                return true;
            }
            return isBalanced(root.left) && isBalanced(root.right) && (Math.abs(deep(root.left) - deep(root.right)) <= 1);
        }
        
        public int deep(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return Math.max(deep(root.left), deep(root.right)) + 1;
        }
    }
    java 复制代码
    // 方法二
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if (root == null) {
                return true;
            }
            if (root.left == null && root.right == null) {
                return true;
            }
            return deep2(root) != -1;
        }
    
        public int deep2(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = deep2(root.left);
            int right = deep2(root.right);
            if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
                return -1;
            }
            return Math.max(left, right) + 1;
        }
    }
相关推荐
南境十里·墨染春水12 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
@insist12312 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试
一只齐刘海的猫17 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏11118 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
IronMurphy19 小时前
【算法五十七】146. LRU 缓存
算法·缓存
凌波粒19 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle19 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂20 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠20 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法