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