最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實現(xiàn)LeetCode(111.二叉樹的最小深度)

 更新時間:2021年07月23日 14:32:12   作者:Grandyang  
這篇文章主要介紹了C++實現(xiàn)LeetCode(111.二叉樹的最小深度),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下

[LeetCode] 111. Minimum Depth of Binary Tree 二叉樹的最小深度

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7

return its minimum depth = 2.

二叉樹的經(jīng)典問題之最小深度問題就是就最短路徑的節(jié)點個數(shù),還是用深度優(yōu)先搜索 DFS 來完成,萬能的遞歸啊。首先判空,若當(dāng)前結(jié)點不存在,直接返回0。然后看若左子結(jié)點不存在,那么對右子結(jié)點調(diào)用遞歸函數(shù),并加1返回。反之,若右子結(jié)點不存在,那么對左子結(jié)點調(diào)用遞歸函數(shù),并加1返回。若左右子結(jié)點都存在,則分別對左右子結(jié)點調(diào)用遞歸函數(shù),將二者中的較小值加1返回即可,參見代碼如下:

解法一:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        if (!root->left) return 1 + minDepth(root->right);
        if (!root->right) return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};

我們也可以是迭代來做,層序遍歷,記錄遍歷的層數(shù),一旦遍歷到第一個葉結(jié)點,就將當(dāng)前層數(shù)返回,即為二叉樹的最小深度,參見代碼如下:

解法二:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            ++res;
            for (int i = q.size(); i > 0; --i) {
                auto t = q.front(); q.pop();
                if (!t->left && !t->right) return res;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return -1;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/111

類似題目:

Binary Tree Level Order Traversal

Maximum Depth of Binary Tree

參考資料:

https://leetcode.com/problems/minimum-depth-of-binary-tree/

https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/36153/My-concise-c%2B%2B-solution

https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/36071/BFS-C%2B%2B-8ms-Beats-99.94-submissions

到此這篇關(guān)于C++實現(xiàn)LeetCode(111.二叉樹的最小深度)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)二叉樹的最小深度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

祁门县| 玛沁县| 平湖市| 唐河县| 西安市| 东台市| 铜陵市| 枣庄市| 石狮市| 长垣县| 乐安县| 金山区| 阳城县| 固原市| 永昌县| 芷江| 江安县| 鲁山县| 乌拉特前旗| 拉孜县| 宽城| 湘阴县| 吉林市| 绿春县| 双流县| 九台市| 六枝特区| 华容县| 宁夏| 芦山县| 开原市| 红河县| 秦皇岛市| 垫江县| 寿阳县| 苍梧县| 肥乡县| 招远市| 白河县| 武夷山市| 柞水县|