判断一棵树是否是二叉平衡树

主要就是判断二叉树深度进行改造。
判断条件为左树为平衡树,右树为平衡树,并且左树的高度和右树的高度插不超过-1;
public class IsAVL {
public static class Node{
private Node left;
private Node right;
private int value;
public Node(int value){
this.value = value;
}
}
public static int isAVL(Node head){
if(head==null){
return 0;
}
int leftdepth = isAVL(head.left);//左树深度
int rightdepth = isAVL(head.right);//右树深度
if(leftdepth==-1||rightdepth==-1){ //在后面设置,如果不符合则返回-1;
return -1;
}
int depth = Math.abs(leftdepth-rightdepth)>1?-1:leftdepth>rightdepth?leftdepth+1:rightdepth+1;
//如果左子树深度和右子树深度差超过1,则返回-1,否则返回两种之中大的那个,并且加一,
//加一是因为原来的子树的,现在的是父节点,需要加一。
return depth;
}
}
总结:二叉树深度,加递归的变形。
原文地址:https://www.cnblogs.com/liuwentao/p/9379701.html