1. public boolean isBalanced(TreeNode root) {
    2. if (root == null) return true;
    3. //分别计算左子树和右子树的高度
    4. int left = height(root.left);
    5. int right = height(root.right);
    6. //这两个子树的高度不能超过1,并且他的两个子树也必须是平衡二叉树
    7. return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    8. }
    9. //计算树中节点的高度
    10. public int height(TreeNode root) {
    11. if (root == null) return 0;
    12. return Math.max(height(root.left), height(root.right)) + 1;
    13. }