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 int height(TreeNode root) //求一个二叉树的高度
{
int right,left;
if(root == null)
return 0;
left = height(root.left) + 1;
right = height(root.right) + 1;
return Math.max(left,right);
}
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int left = height(root.left);
int right = height(root.right);
int diff = left - right; //如果一个子树高度差大于1
if(diff < -1 || diff > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}