思路:写一个函数treeDepth
来返回树的高度
注意点:只递归判断左右子树是否都为平衡二叉树是不够的,因为会存在例外,比如左子树是深度为1的平衡二叉树,右子树是深度为3的平衡二叉树,但事实上这整棵树并不是平衡二叉树。
所以我们的判断条件应该变成左右子树都是平衡二叉树 && 左右子树深度差小于2
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int leftHeight = treeDepth(root.left);
int rightHeight = treeDepth(root.left);
// 判断左子树和右子树是不是平衡的
return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int treeDepth(TreeNode root) {
if (root == null) return 0;
int leftHeight = treeDepth(root.left);
int rightHeight = treeDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
public boolean isBalanced2(TreeNode root) {
if (root == null) return true;
//是否满足平衡二叉树的条件 && 左子树和右子树是否满足平衡二叉树的条件
return Math.abs(treeHeight(root.left) - treeHeight(root.right)) <= 1 && isBalanced2(root.left) && isBalanced2(root.right);
}
public int treeHeight(TreeNode root){
if (root == null) return 0;
return Math.max(treeHeight(root.left), treeHeight(root.right)) + 1;
}