采用自底向上的递归求法。
要点:
(1)在递归的过程中,由于最小深度是从根节点到最近的叶子结点的结点数量,因此如果根节点的一侧为空,不能算作最小深度(必须要有叶子结点才能计算深度,只有根节点则深度为1)。
(2)当结点的某一侧为空的时候,返回深度,即左+右+1(根节点)
(3)若两侧都不为空的时候,返回最小深度的一侧+1(根节点)
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):
if not root:
return 0
leftHeight = self.minDepth(root.left)
rightHeight = self.minDepth(root.right)
if not leftHeight or not rightHeight:
return leftHeight + rightHeight + 1
else:
return min(leftHeight, rightHeight) + 1
node = TreeNode()
a = Solution()
b = a.minDepth(node)
print(b)