[Leetcode][第111题][JAVA][BFS][二叉树的最小深度][BFS][递归]
【問題描述】[簡單]
【解答思路】
1. 遞歸
自下而上
基本情況/結(jié)束條件 :
葉子節(jié)點的定義是左孩子和右孩子都為 null 時叫做葉子節(jié)點
當(dāng) root 節(jié)點左右孩子都為空時,返回 1
當(dāng) root 節(jié)點左右孩子有一個為空時,返回不為空的孩子節(jié)點的深度
當(dāng) root 節(jié)點左右孩子都不為空時,返回左右孩子較小深度的節(jié)點值
遞推關(guān)系:遍歷二叉樹
復(fù)雜度
代碼可以進(jìn)行簡化,當(dāng)左右孩子為空時 m1和 m2 都為 0,可以和情況 2 進(jìn)行合并,即返回 m1+m2+1
class Solution {public int minDepth(TreeNode root) {if(root == null) return 0;int m1 = minDepth(root.left);int m2 = minDepth(root.right);//1.如果左孩子和右孩子有為空的情況,直接返回m1+m2+1//2.如果都不為空,返回較小深度+1return root.left == null || root.right == null ? m1 + m2 + 1 : Math.min(m1,m2) + 1;} } 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;} }2. BFS廣度優(yōu)先遍歷
一個優(yōu)化的方法是利用廣度優(yōu)先搜索,我們按照樹的層去迭代,第一個訪問到的葉子就是最小深度的節(jié)點,這樣就不用遍歷所有的節(jié)點了。
1.特判
2.root入隊 ,左右節(jié)點非空入隊
3.找到第一個左右節(jié)點均為空的節(jié)點即是答案
時間復(fù)雜度:O(N) 空間復(fù)雜度:O(N)
【總結(jié)】
1. 相關(guān)題目
[Leetcode][第104題][JAVA][二叉樹的最大深度][遞歸][BFS]
2.遞歸
在實現(xiàn)遞歸函數(shù)之前,有兩件重要的事情需要弄清楚:
遞推關(guān)系:一個問題的結(jié)果與其子問題的結(jié)果之間的關(guān)系。
基本情況:不需要進(jìn)一步的遞歸調(diào)用就可以直接計算答案的情況??衫斫鉃檫f歸跳出條件。
一旦我們計算出以上兩個元素,再想要實現(xiàn)一個遞歸函數(shù),就只需要根據(jù)遞推關(guān)系調(diào)用函數(shù)本身,直到其抵達(dá)基本情況。
3.遞歸模板套路
遞歸模板套路
由下到上
有上到下
區(qū)別
參考鏈接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/li-jie-zhe-dao-ti-de-jie-shu-tiao-jian-by-user7208/
參考鏈接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/java-di-gui-he-fei-di-gui-liang-chong-fang-shi-de-/
遞歸學(xué)習(xí)資料:https://leetcode-cn.com/circle/article/koSrVI/
總結(jié)
以上是生活随笔為你收集整理的[Leetcode][第111题][JAVA][BFS][二叉树的最小深度][BFS][递归]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PVID、Access、Trunk、Hy
- 下一篇: Question of the Day: