public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return depth(root)>=0;
}
public int depth(TreeNode root){
if(root==null){
return 0;
}
int left=depth(root.left);
int right=depth(root.right);
if(left==-1||right==-1||Math.abs(left-right)>1){
return -1;
}else{
return Math.max(left,right)+1;
}
}
}
2021-12-04(JZ79 判断是不是平衡二叉树)
最新推荐文章于 2025-12-19 15:39:34 发布
该博客主要讨论如何判断一个二叉树是否平衡。提供的Java代码实现了一个名为`Solution`的类,其中包含两个方法:`IsBalanced_Solution`用于检查树是否平衡,`depth`用于计算树的深度。如果树的左右子树深度之差大于1,则认为树不平衡,返回-1;否则返回最大深度加1。
172万+

被折叠的 条评论
为什么被折叠?



