本题目如下:
【leetcode】111:二叉树的最小深度

 

 这题目和二叉树的最大深度的题目有异曲同工之妙,代码如下:

# 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:
            return 0
        if not root.left and not root.right:
            return 1

        min_depth = 10**10
        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

求解最大深度的代码:

# 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 maxDepth(self, root: TreeNode) -> int:
        if root==None:
            return 0
        return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))

一定要区分开这两者之间的不同。

相关文章:

  • 2022-12-23
  • 2021-11-14
  • 2020-06-15
  • 2021-11-01
  • 2022-01-05
  • 2021-07-10
猜你喜欢
  • 2021-07-27
  • 2021-12-14
  • 2021-12-14
  • 2021-11-02
  • 2021-05-19
  • 2021-07-13
  • 2022-12-23
相关资源
相似解决方案