数据结构
class BinTree {
public Object data;
public BinTree left;
public BinTree right;
}
第 1 题
现一个函数检查一颗二叉树是否平衡
public class TreeAndGraph{
/**
* 第 4.1 题,检查一颗二叉树是否平衡
*/
public static boolean isAVL(BinTree root) {
if (root == null) {
return true;
}
int hightDiff = getTreeHight(root.left) - getTreeHight(root.right);
if(hightDiff > 1 || hightDiff < -1){
return false;
}
return isAVL(root.left) && isAVL(root.right);
}
/**
* 获取树的深度
*/
public static int getTreeHight(BinTree node) {
if (node == null)
return 0;
return Math.max(getTreeHight(node.left), getTreeHight(node.right)) + 1;
}
}