day 12-13 算法:二叉樹最大最小深度,生成有效括號組合

1. 題目

  1. 二叉樹的最大深度:給定一個二叉樹,找出其最大深度(離根節點最遠的路徑節點個數)
  2. 二叉樹的最小深度:給定一個二叉樹,找出其最小深度(離根節點最近的路徑節點個數)
  3. 生成有效的括號組合:給定數字n,寫出一個函數,把所有閉合的括號組合輸出,n代表生成括號的對數。

2. 算法題解題

2.1 二叉樹的最大深度:給定一個二叉樹,找出其最大深度(離根節點最遠的路徑節點個數)

解法1:深度優先DFS,遞歸
分別將左右子樹的最大深度算出來再加1即當前二叉樹的最大深度。
時間複雜度O(n),空間複雜度O(1)

public int maxDepth(TreeNode root){
    if (root == null){
        return 0;
    }else{
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        int max = Math.max(left, right) + 1;

        return max;
    }
}

2.2 二叉樹的最小深度:給定一個二叉樹,找出其最小深度(離根節點最近的路徑節點個數)

解法1:深度優先DFS,遞歸
分別將左右子樹的最小深度算出來再加1即當前二叉樹的最小深度。
時間複雜度O(n),空間複雜度O(1)

public int minDepth (TreeNode root){
    if (root == null)
        return 0;
    if (root.left== null && root.right == null)
        return 1;

    int minDepth = Integer.MIN_VALUE;
    if (root.left != null)
        minDepth = Math.min(minDepth(root.left), minDepth);

    if (root.right != null)
        minDepth = Math.min(minDepth(root.right), minDepth);

    return minDepth + 1;
}

解法2: 廣度優先搜索,迭代
使用隊列輔助,按順序取出TreeNode,只要第一個節點是葉子節點,那麼就返回當前節點的深度即可。

public int minDepth(TreeNode root){

    LinkedList<Pair<TreeNode, Integer>> pairs = new LinkedList<>();

    if (root == null)
        return 0;
    //將根節點放入隊列
    pairs.add(new Pair<TreeNode, Integer>(root, 1));

    int minDepth = 0;
    while (!pairs.isEmpty()){
        // 先進先出
        Pair<TreeNode, Integer> pair = pairs.poll();
        TreeNode node = pair.first;
        minDepth = pair.second;

        if (node.left == null && node.right == null)
            break;

        if (node.left != null)
            pairs.add(new Pair<TreeNode, Integer>(node.left, minDepth +1));
        if (node.right != null)
            pairs.add(new Pair<TreeNode, Integer>(node.right, minDepth + 1));
    }
    return minDepth;
}

2.3 生成有效的括號組合:給定數字n,寫出一個函數,把所有閉合的括號組合輸出,n代表生成括號的對數

解法1: 回溯法
判斷括號是否有效,再繼續添加有效括號,直到左右括號匹配,並且字符串長度爲2*n時,添加到集合中。再執行遞歸剩餘的邏輯,不斷窮舉,這個問題比較抽象。
時間複雜度O(2n) 空間複雜度 O(n)
public static List generateParenthesis(int n){
List combinations = new ArrayList<>();

    addGenerateOneByOne(combinations, "", 0, 0 ,n);
    return combinations;
}

private static void addGenerateOneByOne(List<String> combinations, String s, int open, int close, int max) {
    
    if (s.length() == max *2)
        combinations.add(s);
    if (open < max)
        addGenerateOneByOne(combinations, s.concat("("), open +1, close, max);

    if (close < open)
        addGenerateOneByOne(combinations, s.concat(")"), open, close + 1, max);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章