平衡二叉树
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
自底向上的递归,如果两个子树的高度差大于1,则返回-1,说明不平衡了,当有一个子树为-1时,说明整个二叉树都是不平衡的。时间复杂度和空间复杂度都为O(n)
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return getDepth(root) == -1 ? false : true;
}
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 : 1 + Math.max(leftDepth, rightDepth);
}