LeetCode算法题:平衡二叉树isBalanced

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

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

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

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

3

/
9 20
/
15 7
返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

   1
  / \
 2   2
/ \

3 3
/
4 4
返回 false 。

递归,每遍历一个节点,判断左右子树的高度差,如果高度差大于1,那么就说明不平衡,将isBalanced置为-1。

class Solution {
    public boolean isBalanced(TreeNode root) {
        int[] isBalanced = {1};
        isBalanced(root,isBalanced);
        return isBalanced[0] > 0;
    }
    private int isBalanced(TreeNode root,int[] isBalanced) {
        if(root == null)return 0;
        int lh = isBalanced(root.left,isBalanced);
        int rh = isBalanced(root.right,isBalanced);
        if(Math.abs(lh - rh) > 1)
            isBalanced[0] = -1;
        return Math.max(lh,rh) + 1;
    }
}
class Solution {
    public boolean isBalanced(TreeNode root) {
        return isBalanced2(root) >= 0;
    }
    private int isBalanced2(TreeNode root) {
        if(root == null)return 0;
        int left_height = isBalanced2(root.left);
        int right_height = isBalanced2(root.right);
        if(left_height >= 0 && right_height >= 0 && Math.abs(left_height - right_height) <= 1) 
            return Math.max(left_height,right_height) + 1;
        else return -1;
    }
}
发布了352 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43777983/article/details/104962412