平衡二叉树的定义: 空树或者左右子树的高度差不超过1且左右子树也是平衡二叉树。
需要用到计算深度的方法:
public int depth(TreeNode root) {
if (root ==
null)
return 0;
int left = depth(root.left);
int right = depth(root.right);
return Math.max(left, right) +
1;
}
根据平衡二叉树的定义写代码:
public boolean isBalanced(TreeNode root) {
if (root ==
null)
return true;
if (Math.abs(depth(root.left) - depth(root.right)) >
1)
return false;
else return isBalanced(root.left) && isBalanced(root.right);
}