Loading...

从上到下-判断是不是平衡二叉树

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

求解代码

平衡二叉树的核心判断条件:

  • 当前节点的左右子树高度差小于等于1;

  • 当前节点的左右子树本身也是平衡二叉树;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
  public boolean IsBalanced_Solution (TreeNode pRoot) {
       if(pRoot == null){
        return true;
       }

       int left = depth(pRoot.left);
       int right = depth(pRoot.right);

       return Math.abs(left-right)<=1&&IsBalanced_Solution(pRoot.left)&&IsBalanced_Solution(pRoot.right);
}

    public int depth(TreeNode root) {
        if(root == null){
            return 0;
        }

        return Math.max(depth(root.left),depth(root.right))+1;
    }
最后更新于 2026-04-05 17:35:33
Code Road Record