leetcode 111. 二叉树的最小深度
生活随笔
收集整理的這篇文章主要介紹了
leetcode 111. 二叉树的最小深度
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
思路
遞歸解法,思路直接看注釋吧~
注意對(duì)于最小深度定義,有一個(gè)小坑,下面這棵樹的結(jié)果應(yīng)該是2,而不是1,為此我專門加了一個(gè)判斷:
如果根部只有一個(gè)孩子,則另一側(cè)深度恒為1。此時(shí),應(yīng)取有孩子的那一側(cè)的深度!
題解
// Definition for a binary tree node. class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;} }class Solution {public int minDepth(TreeNode root) {if (root != null) {if (root.left == null || root.right == null) {//根部只有一個(gè)孩子,則另一側(cè)深度恒為1。此時(shí)應(yīng)取有孩子一側(cè)的深度return Math.max(getMinDepth(root.left, 1), getMinDepth(root.right, 1));} else {//根部有兩個(gè)孩子,取兩側(cè)最小深度即可return Math.min(getMinDepth(root.left, 1), getMinDepth(root.right, 1));}} elsereturn 0;}public int getMinDepth(TreeNode node, int dep) {if (node != null) {if (node.left != null && node.right != null) {//有兩個(gè)孩子,取較小深度return Math.min(getMinDepth(node.left, dep + 1), getMinDepth(node.right, dep + 1));} else if (node.left != null || node.right != null) { //只有一個(gè)孩子,取較大深度return Math.max(getMinDepth(node.left, dep + 1), getMinDepth(node.right, dep + 1));} else {//沒有孩子,則是葉子節(jié)點(diǎn)return dep + 1;}} else return dep;} }前兩次提交被坑了
總結(jié)
以上是生活随笔為你收集整理的leetcode 111. 二叉树的最小深度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SPU解析优化:模块设计与实现,SKU优
- 下一篇: leetcode 119. 杨辉三角 I