• 判断是否为平衡二叉树:节点为空,左右孩子深度差不超过1,且左右孩子也必须平衡(通过计算深度)
  • 函数不可单纯计算深度,还需判断平衡,设置一个不可逆负值为非平衡,则可实现需求
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return treeDepthRec(root) != -2;
    }

    // 判断树的深度,返回-1则不平衡
    public int treeDepthRec(TreeNode root) {
        if(root == null) {
            return 0;
        }

        int left = treeDepthRec(root.left);
        int right = treeDepthRec(root.right);

        if(Math.abs(left - right) > 1) {
            return -2;
        }

        return Math.max(left, right) + 1;
    }
}