0
点赞
收藏
分享

微信扫一扫

Java平衡二叉树

徐一村 2022-04-17 阅读 49

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:

输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:

输入:root = []
输出:true

class Solution {

    public int height(TreeNode root){
        if(root == null) return 0;
        int leftheight = height(root.left);
        int rightheight = height(root.right);
        return (leftheight > rightheight) ? (leftheight+1):(rightheight+1);
    }
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int left = height(root.left);
        int right = height(root.right);
        return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
}

该代码的时间复杂度为O(n*n),将代码可以优化如下:

class Solution {

    public int height(TreeNode root){
        if(root == null) {return 0;}
        int leftheight = height(root.left);
        int rightheight = height(root.right);
        if(leftheight >= 0 && rightheight >= 0 && Math.abs(leftheight - rightheight) <= 1){
            return Math.max(leftheight,rightheight) + 1;
        }else{
            //说明树已经不平衡了
            return -1;
        }
    }
    public boolean isBalanced(TreeNode root) {
        if(root == null) {return true;}

        return height(root) >= 0;
    }
}
举报

相关推荐

0 条评论