应用题-二叉树专题-二叉树的最小深度

管理员
**写法1** ```python # 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: Optional[TreeNode]) -> int: if not root: return 0 # !important: 到叶子结点的最短路径 self.min_h = float( 'inf' ) def minDepth_( r, h ): if not r: return if not r.left and not r.right: if h < self.min_h: self.min_h = h minDepth_( r.left, h + 1 ) minDepth_( r.right, h + 1 ) minDepth_( root, 1 ) return self.min_h ``` **写法2** ```python # 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: Optional[TreeNode]) -> int: if not root: return 0 # 根节点存在 if not root.left and root.right: # 左子树不存在 return 1 + self.minDepth( root.right ) if not root.right and root.left: # 右子树不存在 return 1 + self.minDepth( root.left ) # 左右子树都存在 return 1 + min( self.minDepth( root.left ), self.minDepth( root.right ) ) ```
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧