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.
分治法的应用,通过观察子树是否为平衡树来判断整棵树是否平衡。
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) {
if (maxDepth(root) == -1) {
return false;
}
return true;
}
private int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if (Math.abs(left - right) > 1 || left == -1 || right == -1) {
return -1;
}
return Math.max(left, right) + 1;
}
}