-
题目
java给定一个二叉树,判断它是否是 平衡二叉树 -
示例
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 -
解题思路
- 平衡二叉树 是指该树所有节点的左右子树的深度相差不超过 1。
- 方法一:根据平衡二叉树的概念,递归每一个节点其左右子树的深度,判断是否平衡。
- 方法二:方法一的优化,减少递归次数。当遇到不是平衡二叉树的节点直接返回,不在继续递归。
-
代码(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; } }
LeetCode110 平衡二叉树
biglxl2024-03-23 17:03
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解wzdark5 天前
大规模并行计算中的负载均衡算法研究4Because_of_Her15 天前
并查集-听课笔记码流子5 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环another heaven5 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】wzdark5 天前
从算法设计模式看编程思维的抽象能力42601_962218615 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点