111. 二叉树的最小深度
解法一:递归
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: #递归出口,空节点
return 0
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: #排除根为空
return 0
if not root.left and not root.right: #递归出口,叶节点
return 1
min_depth = sys.maxsize #最小深度,初始设为最大整数
if root.left:
min_depth = min(min_depth, self.minDepth(root.left))
if root.right:
min_depth = min(min_depth, self.minDepth(root.right))
return min_depth + 1解法二:层序
最后更新于