一、题目描述
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
二、题解
方法一:穷举树高
思路
核心思想:只有每个节点的左右子树的高度差 diff <= 1 时,该树才是平衡的。所以,求高度就变成了本题的重点。
算法
- 一开始就求出根节点 root 的左子树高度 DLeft 与右子树高度 RLeft,如果高度查大于 1,那么就不是平衡二叉树;
- 根节点 root 的 DLeft 与 DRight 没问题,不能证明每一棵子树的最大高度都没有问题,所以我们要对每一棵子树都做一遍根节点 root 做过的,即寻找当前结点下的最大子树高度。
- 这相当于穷举每一个结点的高度
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
//求出左右子树的最大深度
int DLeft = findDepth(root.left);
int DRight = findDepth(root.right);
if (Math.abs(DLeft - DRight) > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int findDepth(TreeNode root) {
if (root == null)
return 0;
return Math.max(findDepth(root.left), findDepth(root.right)) + 1;
}
复杂度分析
- 时间复杂度: ,假设某个结点的高度为 h,findDepth 至少将会被调用 h 次。
- 空间复杂度: ,
方法二:自底向上
方法一存在大量的冗余计算。实际上我们可以一步递归到底,然后回溯到某一个结点时,就判断这个结点左右子树的高度差 diff 是否大于 1。
private int findDepth1(TreeNode root) {
if (root == null)
return 0;
int leftD = findDepth(root.left);
if (leftD == -1) return -1;
int rightD = findDepth(root.right);
if (rightD == -1) return -1;
int diff = Math.abs(leftD - rightD);
return diff <= 1 ? Math.max(leftD, rightD) + 1 : -1;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,