法一
public class isAVLTree{
public static boolean isBalance(BSTNode node){
if(node==null)return false;
int min=getHeight(node.left)-getHeight(node.right);//左右子树高度差
return Math.abs(min)>1||isBalance(node.left)||isBalance(node.right);
}
public static int getHeight(BSTNode node){
if(node==null)return 0;//递归出口
int lHeight=getHeight(node.left)+1;//递归求左子树高度
int rHeight=geitHeight(node.right)+1;//求右子高度
return Math.max(lHeight,rHeight);//返回最大的那个
}
}
法二
public class isBalance(BSTNode node){
return isBalance(node,new HashMap<BSTNode,Integer>heightMap);
}
public class isBalance(BSTNode node,HashMap<BSTNode,Integer>heightMap){
if(node==null||(node.left==null&&node.right==null))return false;//根节点为空或左右子树都不存在
boolean b=Math.abs(heightOf(node.left,heightMap)-heightOf(node.right,heightMap))<=1;//高度差不大于1
return b&&isBalance(node.left)&&isBalance(node.right);
}
public int heightOf(BSTNode node,HashMap<BSTNode,Integer>heightMap){
if(node==null)return 0;
Integer height=heightMap.get(node);
if(height!=null)return height;//获得到height则返回
if(node.left==null&&node.right==null){
heightMap.put(node,1);//存储节点和其对应的高度
}
else if(node.left==null){
heightMap.put(node,1+heightOf(node.right,heightMap));//右边递归
}else if(node.right==null){
heightMap.put(node,1+heightOf(node.left,heightMap));//左边递归
}else{
heightMap.put(node,Math.max(heightOf(node.left,heightMap),heightOf(node.right,heightMap)))//左右子树都存在,则取最大的那个;
}
return heightMap.get(node);//返回node对应的高度
}