通过递归,不断地求一个节点的左右子节点的的最大深度,最后看根节点的左右子树的高度差是否大于1。
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)
return true;
if(getDepth(root)==-1)
return false;
return true;
}
public static int getDepth(TreeNode node)
{
if(node==null)
return 0;
int left=getDepth(node.left);
int right=getDepth(node.right);
if (left==-1||right==-1)
return -1;
if(Math.abs(left-right)>1)
return -1;
return Math.max(left, right)+1;
}
}