思路:
空树,或者左右子树的深度差不超过1;public boolean isBalanceTree(TreeNode root){ return getDepth(root)!=-1; } public int getDepth(TreeNode root){ if(root==null){ return 0; } int leftDepth=getDepth(root.left); if(leftDepth==-1){ //左子树不为平衡二叉树,节省空间 return -1; } int rightDepth=getDepth(root.right); if(rightDepth==-1){ //右子树不为平衡二叉树 return -1; } return Math.abs(leftDepth-rightDepth)>1 ? -1 : Math.max(leftDepth, rightDepth)+1; }