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.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private boolean flag=true; //是否为平衡树
public boolean isBalanced(TreeNode root) {
height(root);
return flag;
}
private int height(TreeNode t)
{
if(!flag||t==null)
{
return 0;
}
else
{
int left=height(t.left);
int right=height(t.right);
if(Math.abs(left-right)>1)
{
flag=false;
}
return Math.max(left,right)+1;//返回左右子树最高的作为树的高度
}
}
}