输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树
平衡二叉树(Balanced BinaryTree)又被称为AVL树。它具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
平衡二叉树一般是一个有序树,它具有二叉树的所有性质,其遍历操作和二叉树的遍历操作相同。但是由于其对二叉树施加了额外限制,因而其添加、删除操作都必须保证平衡二叉树的性子被保持。
平衡二叉树中引入了一个概念:平衡二叉树节点的平衡因子,它指的是该节点的两个子树,即左子树和右子树的高度差,即用左子树的高度减去右子树的高度,如果该节点的某个子树不存在,则该子树的高度为0,如果高度差的绝对值超过1就要根据情况进行调整。
代码
这里借助上一篇二叉树深度中计算二叉树深度的代码来计算左子树和右子树的高度差。
-
static class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
-
public TreeNode(int val) {
-
this.val = val;
-
}
-
}
-
-
public static boolean isBalanced(TreeNode root) {
-
if (root == null) {
-
return true;
-
}
-
if (root.left == null && root.right == null) {
-
return true;
-
}
-
-
int leftDepth = treeDepth(root.left);
-
-
int rightDepth = treeDepth(root.right);
-
-
if (Math.abs(leftDepth - rightDepth) > 1) {
-
return false;
-
}
-
-
return isBalanced(root.left) && isBalanced(root.right);
-
}
-
-
private static int treeDepth(TreeNode root) {
-
if (root == null) {
-
return 0;
-
}
-
-
int left = treeDepth(root.left);
-
-
int right = treeDepth(root.right);
-
-
return left >= right ? (left + 1) : (right + 1);
-
}