[leetcode]111.二叉树的最小深度
生活随笔
收集整理的這篇文章主要介紹了
[leetcode]111.二叉树的最小深度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明:葉子節點是指沒有子節點的節點。
示例 1:
輸入:root = [3,9,20,null,null,15,7] 輸出:2?示例 2:
輸入:root = [2,null,3,null,4,null,5,null,6] 輸出:5?提示:
- 樹中節點數的范圍在?[0, 105]?內
- -1000 <= Node.val <= 1000
遞歸解法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution:def minDepth(self, root: TreeNode) -> int:if not root:return 0if not root.left and not root.right:return 1min_depth=10**9if root.left:min_depth=min(self.minDepth(root.left),min_depth)if root.right:min_depth=min(self.minDepth(root.right),min_depth)return min_depth+1總結
以上是生活随笔為你收集整理的[leetcode]111.二叉树的最小深度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑盒测试的用例设计方法
- 下一篇: Pytest入门【1】