LeetCode 110 Balanced Binary Tree 平衡二叉树

LeetCode 110 Balanced Binary Tree

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]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

Solution 1:
这是和求最大深度的结合在一起,可以考虑写个helper函数找到拿到左右子树的深度,然后递归调用isBalanced函数判断左右子树是否也是平衡的,得到最终的结果。时间复杂度O(n^2)

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftDep = depthHelper(root.left);
        int rightDep = depthHelper(root.right);
        if (Math.abs(leftDep - rightDep) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {
            return true;
        }
        return false;
    }
    private int depthHelper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(depthHelper(root.left), depthHelper(root.right)) + 1;
    }

Solution 2:
解题思路:
再来看个O(n)的递归解法,相比上面的方法要更巧妙。二叉树的深度如果左右相差大于1,则我们在递归的helper函数中直接return -1,那么我们在递归的过程中得到左子树的深度,如果=-1,就说明二叉树不平衡,也得到右子树的深度,如果=-1,也说明不平衡,如果左右子树之差大于1,返回-1,如果都是valid,则每层都以最深的子树深度+1返回深度。

    public boolean isBalanced(TreeNode root) {
        return dfsHeight(root) != -1;
    }
    //helper function, get the height
    public int dfsHeight(TreeNode root){
        if (root == null) {
            return 0;
        }
        int leftHeight = dfsHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = dfsHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight, rightHeight) + 1;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值