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;
    }
相關文章
相關標籤/搜索