題目
給定一個二叉樹,找出其最小深度婚苹。
最小深度是從根節(jié)點到最近葉子節(jié)點的最短路徑上的節(jié)點數(shù)量。
說明: 葉子節(jié)點是指沒有子節(jié)點的節(jié)點。
示例:
給定二叉樹 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
解答
-
思路:
- 通過DFS遞歸遍歷目標樹冗澈,一旦遍歷到葉子節(jié)點,馬上返回陋葡;
-
代碼:
def minDepth(self, root: TreeNode) -> int: """ :type root: TreeNode :rtype int (knowledge) 思路: 1. 通過DFS遞歸遍歷目標樹亚亲,一旦遍歷到葉子節(jié)點,馬上返回 """ if root is None: return 0 if root.left and root.right: return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
測試驗證
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
if self:
return "{}->{}->{}".format(self.val, repr(self.left), repr(self.right))
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""
:type root: TreeNode
:rtype int
(knowledge)
思路:
1. 通過DFS遞歸遍歷目標樹腐缤,一旦遍歷到葉子節(jié)點捌归,馬上返回
"""
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
if __name__ == '__main__':
solution = Solution()
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(solution.minDepth(root), "= 2")