判断任意一个节点的两个子树的高度差是否大于1. 还是遍历每个节点获得每个子树的高度并判断当前节点的子树的高度差。将结果返回即可
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
boolean res=true;
public boolean isBalanced(TreeNode root) {
if(root==null)
{
return true;
}
fun(root,0);
return res;
}
int fun(TreeNode root,int h)
{
if( res==false )
{
return h;
}
if(root==null)
{
return h;
}
h++;
if(Math.abs(fun(root.left,h)-fun(root.right,h))>=2)
{
res= false;
}
return Math.max(fun(root.left,h),fun(root.right,h));
}
}