# 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:
#递归法:后序遍历+分治思想
return self.getDepth(root)
def getDepth(self,root)-> int:
#终止条件
if not root:
return 0
#左
leftdepth=self.getDepth(root.left)
#右
rightdepth=self.getDepth(root.right)
#中,逻辑处理与最大深度不同
#左子树为空,右子树不为空,此时最小深度为1+右高度
if root.left is None and root.right is not None:
return 1+rightdepth
#左子树不为空,右子树为空,此时最小深度1+左高度
if root.left is not None and root.right is None:
return 1+leftdepth
#左右子树都不为空
return 1+min(leftdepth,rightdepth)