1. 程式人生 > 其它 >用Python做一款免費音樂下載器、無廣告無彈窗、清爽超流暢哦

用Python做一款免費音樂下載器、無廣告無彈窗、清爽超流暢哦

二叉樹的最小深度

題目:二叉樹的最小深度

《程式設計師程式碼面試指南》第33題 P100 難度:原問題 士★☆☆☆ 進階問題 將★★★★

本題書上有普通解法和進階解法。進階解法用到了遍歷二叉樹的神級方法——Morris遍歷,暫時不看,有空回來補。

下面介紹普通解法。很簡單,就是在遍歷的過程中去發現所有的葉子結點,並且能夠知道該葉子結點的高度。最後找到所有葉子結點高度中的最小值

牛客上沒有這題,力扣上有深度優先搜尋廣度優先搜尋兩種方法。

DFS(時間複雜度O(N),空間複雜度O(H)):

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }

        int min_depth = Integer.MAX_VALUE;
        if (root.left != null) {
            min_depth = Math.min(minDepth(root.left), min_depth);
        }
        if (root.right != null) {
            min_depth = Math.min(minDepth(root.right), min_depth);
        }

        return min_depth + 1;
    }
}

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

不難發現,遞迴直到找到葉子結點後,返回深度1,然後從下往上逐層深度加1,並且每次左子樹和右子樹取最小深度。到第一層根節點處,同樣,找出左子樹和右子樹的最小深度後,再返回深度加1,即加上根節點的深度,就是整個二叉樹的最小深度

BFS(時間複雜度O(N),空間複雜度O(N)):

class Solution {
    class QueueNode {
        TreeNode node;
        int depth;

        public QueueNode(TreeNode node, int depth) {
            this.node = node;
            this.depth = depth;
        }
    }

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<QueueNode> queue = new LinkedList<QueueNode>();
        queue.offer(new QueueNode(root, 1));
        while (!queue.isEmpty()) {
            QueueNode nodeDepth = queue.poll();
            TreeNode node = nodeDepth.node;
            int depth = nodeDepth.depth;
            if (node.left == null && node.right == null) {
                return depth;
            }
            if (node.left != null) {
                queue.offer(new QueueNode(node.left, depth + 1));
            }
            if (node.right != null) {
                queue.offer(new QueueNode(node.right, depth + 1));
            }
        }

        return 0;
    }
}

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

對於廣度優先搜尋進行特別說明:

找到一個葉子節點時,直接返回這個葉子節點的深度。廣度優先搜尋的性質保證了最先搜尋到的葉子節點的深度一定最小

這是因為廣度優先搜尋相當於層序遍歷二叉樹,如果一個節點是葉子結點,說明當前層和之前的所有層都沒有出現過葉子結點,所以第一個搜尋到的葉子結點深度一定是最小的