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. 一棵平衡二叉树即一棵二叉树的所有节点的左右子树的高度差不超过1.
很显然,解这道题需要从得到二叉树的高度的算法修改而来。 获取二叉树的高度的算法:
private int height(TreeNode node) {
if (node == null) {
return 0;
} else {
int i = height(node.left);
int j = height(node.right);
return (i < j) ? j + 1 : i + 1;
}
}
只需要修改下,让树的左右子树的高度差大于1时,返回-1.
public class leetcode110 {
public boolean isBalanced(TreeNode root) {
int res = helper(root);
return res != -1;
}
private int helper(TreeNode node) {
if (node == null) {
return 0;
} else {
int i = helper(node.left);
int j = helper(node.right);
if (i == -1 || j == -1)
return -1;
else {
if (Math.abs(i - j) > 1) return -1;
else
return Math.max(i, j) + 1;
}
}
}
}