题目
解法
public class BSTNode<T extends Comparable<T>> {
T key;
BSTNode<T> left;
BSTNode<T> right;
BSTNode<T> parent;
public BSTNode(T key, BSTNode<T> parent, BSTNode<T> left, BSTNode<T> right) {
this.key = key;
this.parent = parent;
this.left = left;
this.right = right;
}
}
/**
* 获取树的深度,树的深度为左子树深度和右子树深度较大值加1
*
* @param tree
* @return
*/
public static int getTreeDepth(BSTNode<Integer> tree) {
if (tree == null) return 0;
int leftDepth = getTreeDepth(tree.left);
int rightDepth = getTreeDepth(tree.right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
/**
* 判断是否平衡树
*
* 平衡树: 左子树和右子树深度差小于1
*
* @param tree
* @return
*/
public static boolean isBalanceTree(BSTNode<Integer> tree) {
if (tree == null) return true;
int leftDepth = getTreeDepth(tree.left);
int rightDepth = getTreeDepth(tree.right);
if (Math.abs(leftDepth - rightDepth) > 1) return false;
return isBalanceTree(tree.left) && isBalanceTree(tree.right);
}