了解平衡二叉树
首先,平衡二叉树,也叫平衡二叉搜索树,即AVL树;其具有以下特点:
①:它是一颗空树;
②:或者它的左右高度差不超过1,并且其左右两颗树都是平衡二叉树;
③:其高度一般都维持在O(log(n)),也就是其搜索时间复杂度;
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路
首先,可以根据其性质去判断,要满足其性质,所以要么它是一颗空数或者左右子树差最多为1,并且左子树是一颗二叉树,右子树也是一颗二叉树。可以用递归去做这一道题;
代码实现如下
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
return Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private int maxDepth(TreeNode root){
if(root == null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
由于上面的代码实现递归左右节点的时候,下层节点多次被判断,时间复杂度较低,我们可以采用以下方式,这种方式的好处只要一个“子树”不满足条件,直接终止,返回-1;
代码实现如下
public boolean IsBalanced_Solution(TreeNode root) {
return getDepth(root)!=-1;
}
private int getDepth(TreeNode root){
if(root == null){
return 0;
}
//递归我左节点
int left = getDepth(root.left);
if(left == -1){
return -1;
}
//递归我右节点
int right = getDepth(root.right);
if(right == -1){
return -1;
}
//左右节点高度如果大于1,那么就返回-1,反之返回左右的最大高度+1
return Math.abs(left-right)>1?-1:1+Math.max(left,right);
}