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 ofeverynode never differ by more than 1.
Solution 1: 用-1表示unbalanced,> = 0表示高度
public boolean isBalanced(TreeNode root) {
return helper(root) != -1;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
if (left == -1) {
return -1;
}
int right = helper(root.right);
if (right == -1) {
return -1;
}
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
Solution 2: 对每个node求左右子树的高度,比较
public boolean isBalanced(TreeNode root) {
// Write your solution here.
if (root == null) {
return true;
}
if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}