思考过程
高度平衡的二叉树的条件是:
1.左节点是高度平衡的二叉树
2.且右节点是高度平衡的二叉树
3.且左右节点的高度差小于等于1
所以可以想到用递归的方法
同时还需要一个方法 getDepth ,用于获取二叉树的深度,该方法也是使用递归的解法,
代码实现
获取二叉树深度:
当节点为空时,返回深度0;
当节点不为空时,返回max(左节点深度+1,右节点深度+1);
代码如下:
private int getDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(1 + getDepth(root.left), 1 + getDepth(root.right));
}
判断是否是高度平衡的二叉树:
如果节点为空,返回true;
如果节点不为空,返回左节点是高度平衡的二叉树,且右节点是高度平衡的二叉树,且左右节点深度差小于等于1
代码如下:
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return isBalanced(root.left)
&& isBalanced(root.right)
&& Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1;
}
执行结果
优化
以上的代码可以通过,但是内存消耗较大,可以在此基础上稍作优化:
当左节点或者右节点有一个为空时,只需要判断另外一个节点的深度是否小于等于1即可
代码如下:
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (root.left != null && root.right != null) {
return isBalanced(root.left)
&& isBalanced(root.right)
&& Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1;
} else if (root.left == null) {
return getDepth(root.right) <= 1;
} else {
return getDepth(root.left) <= 1;
}
}
执行结果
较之前稍有改善,但时间复杂度依然较高(O(n²)),并非最优解法。
算法复杂度分析
时间复杂度:O(n²),其中 n是二叉树中的节点个数。
空间复杂度:O(n),其中 n 是二叉树中的节点个数。
方法一,自顶向下的递归,和我个人思路一致。
方法二,自底向上的递归,方法一由于是自顶向下递归,因此对于同一个节点,函数 getDepth 会被重复调用,导致时间复杂度较高。如果使用自底向上的做法,则对于每个节点,函数 getDepth 只会被调用一次。自底向上递归的做法类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 −1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。
代码如下:
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
方法二时间复杂度:O(n),空间复杂度:O(n)。