leetcode 110 平衡二叉树

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        else{
            boolean isHeightNear = Math.abs( height(root.left) - height(root.right) ) <=1; 
            return isHeightNear && isBalanced(root.left) && isBalanced(root.right);
        }
    }
    int height(TreeNode a){
        if(a==null) return 0;
        else return 1+Math.max(height(a.left),height(a.right));
    }
}

直接法:

判断左右节点高度差是否小于1 , 如果是 ,则递归判断左右节点的左右节点是否平衡

时间复杂度O(nlogn)

原因是有两重的递归 重复遍历了

解决方法是在height计算时顺便把是否balance也判断了

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
         
        return heightAndCheckBalance(root)!=-1;
        
    }
    int heightAndCheckBalance(TreeNode node){//这个函数,如果发现不平衡则返回-1, 否则会返回高度
        if(node==null) return 0;

        int leftHeight=heightAndCheckBalance(node.left);
        if(leftHeight==-1) { return -1;}

        int rightHeight = heightAndCheckBalance(node.right);
        if(rightHeight==-1) {return -1;}

        if(Math.abs(leftHeight-rightHeight)>1){return -1;}

        return 1+Math.max(leftHeight, rightHeight);
    }
}

时间复杂度降到O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值