# 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: #处理特殊情况,当root为空时返回0
return 0
if not root.left and not root.right: #表示当前结点为叶子节点时
return 1 #当前结点有一层
min_depth = 10**9 #设置一个极大的数
if root.left: #存在左子树
min_depth = min(self.minDepth(root.left), min_depth)
if root.right:
min_depth = min(self.minDepth(root.right), min_depth)
#递归调用中不同层的的函数minDepth其参数min_depth的储存位置不同,所以内层的min_depth有变化外层的也没有变
return min_depth + 1 #每调用一次,说明有一个结点,深度加一
leetcode---二叉树的最小深度
最新推荐文章于 2022-05-06 20:22:38 发布