思路:递归+深度优先搜索
class Solution:
def minDepth(self, root: TreeNode) -> int:
# 边界条件
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = 10 ** 9
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
- 二叉树的最大深度
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1