【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))

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

posted @ 2021-10-13 21:52  Geeksongs  阅读(5)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.