题目地址:
https://www.lintcode.com/problem/balanced-binary-tree/description
给定一棵二叉树,判断其是否平衡。
平衡二叉树的定义是,首先空树是平衡二叉树;如果非空,则必须其左右子树的高度差小于等于 1 1 1,并且其左右子树也分别是平衡二叉树。
上面的定义是递归定义。如果直接按照这个定义去判断的话,会导致子树的高度被多次计算(在树的高度的计算是用递归来写的情况下)。为了避免这一点,我们可以在计算某棵子树的高度的同时就去返回该树是不是平衡的,比如如果不平衡,就返回 − 1 -1 −1,否则返回高度。这样一来,每课子树的高度和是否平衡的信息就可以在递归调用的时候得到传递了。具体代码如下:
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
// write your code here
return depth(root) != -1;
}
// 如果root不平衡,则返回-1;否则返回其高度
private int depth(TreeNode root) {
if (root == null) {
return 0;
}
int l = depth(root.left);
int r = depth(root.right);
// 如果有一个是-1,说明左右子树有一个不平衡,则返回-1;
// 若左右都平衡但是左右高度差大于1,说明本树不平衡,也返回-1
if (l == -1 || r == -1 || Math.abs(l - r) >= 2) {
return -1;
} else {
return Math.max(l, r) + 1;
}
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n)(每个节点仅被计算过一次),空间 O ( h ) O(h) O(h)。