[LeetCode] 110. Balanced Binary Tree

45 篇文章 0 订阅

原题链接:https://leetcode.com/problems/balanced-binary-tree/

1. 题目介绍

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

给定一个二叉树,判断它是否为平衡二叉树。平衡二叉树就是指每个节点的左右子树长度相差不超过1的二叉树。

Example 1:
Given the following tree [3,9,20,null,null,15,7]:
在这里插入图片描述
Return true.

Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
在这里插入图片描述
Return false.

2. 解题思路

方法1 计算左右子树高度

可以计算出每个节点的左右子树高度差,如果高度差大于1,则返回false。如果没有节点,则相当于两个子树的高度都是0,则返回true。其他的情况,使用递归计算左右子树是否为平衡的,将左子树和右子树的情况进行与运算返回。
实现代码

class Solution {
    public boolean isBalanced(TreeNode root) {
        return cur(root);
    }
    
    public boolean cur(TreeNode root){
        if(root == null){
            return true;
        }
        int diff = Math.abs( depth(0,root.left) - depth(0,root.right) );
        if(diff>1){
            return false;
        }
        return cur(root.left) && cur(root.right);
    }
    
    public int depth(int d, TreeNode root){
        if(root == null){
            return d;
        }
        if(root.left == null && root.right == null){
            return d+1;
        }
        return Math.max(depth(d+1,root.left) , depth(d+1,root.right)  ) ;
    }
}

方法2 直接返回是否为平衡树

注:该方法来自 https://www.cnblogs.com/grandyang/p/4045660.html 有兴趣的读者可以直接去看原文。

是如果我们发现子树不平衡,则不计算具体的深度,而是直接返回-1。如果是平衡的,就返回具体的深度。
对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1,此方法时间复杂度O(N),空间复杂度O(H),参见代码如下:

class Solution {
    public boolean isBalanced(TreeNode root) {
        return(findDepth(root) == -1 ? false : true);
    }
    
    public int findDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        
        //判断左子树是否为平衡树,如果不是直接返回-1,不必做多余计算
        int left = findDepth(root.left);
        if(left == -1){
            return -1;
        }
        //判断右子树是否为平衡树,如果不是直接返回-1,不必做多余计算
        int right = findDepth(root.right);
        if(right == -1){
            return -1;
        }
        
        //此时左右子树都是平衡树了
        //现在开始判断以root为根节点的树是不是平衡树
        //如果不是直接返回-1
        int diff = Math.abs(left - right);
        if(diff > 1){
            return -1;
        }
        
        //到这一步,已经确认了左子树、右子树、root树本身都是平衡树
        //可以返回root树的真实长度了
        return 1 + Math.max(left,right);   
    }
}

3. 参考资料

https://www.cnblogs.com/grandyang/p/4045660.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值