LeetCode 110 Balanced Binary Tree 平衡二叉树

LeetCode 110 Balanced Binary Treenode

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.this

Example 1:code

Given the following tree [3,9,20,null,null,15,7]:递归

3
   / \
  9  20
    /  \
   15   7

Return true.ip

Example 2:leetcode

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

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

Return false.it

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

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;
    }
相关文章
相关标签/搜索