分析
因为给出的是二叉搜索树,所以只要判断平衡因子是否为1就可以
Java版本实现
//获取树的深度
int getDepth(Node<T> root , int initDeep){
if(root == null)
return initDeep;
int leftDeep = initDeep;
int rightDeep = initDeep;
if(root.getLeft() != null)
leftDeep = getDepth(root.getLeft() , initDeep++);
if(root.getRight() != null)
rightDeep = getDepth(root.getRight(), initDeep++);
return leftDeep > rightDeep ? leftDeep : rightDeep;
}
//判断树是否失去平衡
boolean unBanlace(Node<T> root) {
if(root == null)
return false;
int leftHeight = getDepth(root.getLeft(), 1);
int rightHeight = getDepth(root.getRight(), 1);
return Math.abs(leftHeight - rightHeight) > 1;
}//判断是否AVL树
boolean isAVL() {
// if(root == null)
// return false;
// int left = getDepth(root.getLeft(), 1);
// int right = getDepth(root.getRight(), 1);
// if(Math.abs(left - right) > 1)
// return false;
// return true;
return unBanlace(root) == false;
}