public static int getDeep(BinaryTree root )
{
if(root==null)
{
return 0;
}
int nleft = getDeep(root.left);
int nright = getDeep(root.right);
return nleft > nright ? nleft+1 : nright +1;
}public static boolean isBalanced(BinaryTree root) {
if(root == null)return true;
int in = getDeep1(root);
if(in >= 0)
return true;
else
return false;
}
public static int getDeep(BinaryTree root )
{
if(root==null)
{
return 0;
}
int nleft = getDeep(root.left);
int nright = getDeep(root.right);
//System.out.println("root:"+root.value); 可以将中间结果打印出来看详细过程
//System.out.println("left:"+nleft);
//System.out.println("right:"+nright);
if(nright <0 || nleft < 0) return -1; //如果小于0,就说明上一步的左右子树相差必然超过1了,所以直接返回
if(Math.abs(nleft-nright) >1)return -1; //左右子树相差超过1,返回-1
return nleft > nright ? nleft+1 : nright +1; //返回二叉树的深度
}版权声明:本文为博主原创文章,转载请注明出处。
原文:http://blog.csdn.net/u014307117/article/details/47818083