Description
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 depth of the two subtrees of every node never differ by more than 1.
Example
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
Solution
要判断一棵二叉树是否平衡,先判断左右子树的高度差是否超过1,再递归地判断左右子树是否平衡。因此可以很容易地想到最直观的做法:
public class Solution2 {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int left = depth(root.left);
int right = depth(root.right);
return Math.abs(left-right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode node) {
if(node == null)
return 0;
return Math.max(depth(node.left), depth(node.right)) + 1;
}
}
由于depth()
方法要遍历该树的所有节点,时间复杂度为O(n),而判断每个子树是否平衡都需要使用它来得到其子树的深度,因此总共的时间复杂度为O(n^2)。可以看出,由于depth()
的重复使用导致该算法做了许多没必要的操作。
如果把上面这种解法理解成由上至下重复的计算深度并判断是否平衡,那么以下的解法则是由下至上的逐步计算高度并判断是否平衡:
public class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode node) {
if(node == null)
return 0;
int left = height(node.left);
if(left == -1) return -1;
int right = height(node.right);
if(right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}
这种解法无需重复的计算每个子树的深度,而是由下至上的一步步构建完成,在构建的过程中如果发现不满足平衡条件也就是左右子树的高度差大于1了就直接返回-1,否则就返回当前的高度。