题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树(AVL):它又称为AVL树,它是一棵空树或者它的左右子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
public class BalanceTree {
// 是否为平衡二叉树
static boolean isBalanced = true;
private static int depth(TreeNode head) {
if (head == null || !isBalanced) {
return 0;
}
// 分别遍历左子树和右子树,和求深度的过程是相同的
int left = depth(head.left);
int right = depth(head.righ);
// 如果深度之差超过1了就不是平衡二叉树了
if (Math.abs(left - right) > 1) {
isBalanced = false;
}
return Math.max(left, right) + 1;
}
private static boolean isBlance(TreeNode head) {
depth(head);
return isBalanced;
}
public static void main(String[] args) {
TreeNode head = new TreeNode(6);
head.left = new TreeNode(4);
head.righ = new TreeNode(8);
head.left.left = new TreeNode(1);
head.left.righ = new TreeNode(5);
head.left.left.righ = new TreeNode(2);
head.righ.righ = new TreeNode(9);
System.out.println(isBlance(head));
}
}
class TreeNode {
int val;
TreeNode left = null;
TreeNode righ = null;
public TreeNode(int val) {
this.val = val;
}
}