2025/09/08 LeetCode 111.二叉树的最小深度

111. 二叉树的最小深度 - 力扣(LeetCode)

解法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 minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = collections.deque([root])
        min_depth = 0
        while queue:
            min_depth += 1
            for _ in range(len(queue)):
                node = queue.popleft()
                if not node.left and not node.right:
                    return min_depth
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

 注意审题:

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

 

解法2.递归写法 【重点:薄弱部分】

(1)后序遍历递归

写法①

class Solution:
    def getDepth(self, node):
        if not node:
            return 0
        leftDepth = self.getDepth(node.left) #
        rightDepth = self.getDepth(node.right) #

        # 当一个左子树为空,右不为空,这时并不是最低点
        if node.left and not node.right:
            return 1 + leftDepth

        # 当一个右子树为空,左不为空,这时并不是最低点
        if not node.left and node.right:
            return 1 + rightDepth
            
        result = 1 + min(leftDepth, rightDepth)
        return result

    def minDepth(self, root: Optional[TreeNode]) -> int:
        self.getDepth(root)

写法② 简洁写法

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if root.left and not root.right:
            return 1 + self.minDepth(root.left)
        if not root.left and root.right:
            return 1 + self.minDepth(root.right)
        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

(2)前序遍历递归

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        self.result = float('inf')
        if not root:
            return 0
        self.getDepth(root, 1)
        return self.result

    def getDepth(self, node, depth):
        if not node:
            return 
        if not node.left and not node.right:
            self.result = min(self.result, depth)
        if node.left:
            self.getDepth(node.left, depth + 1)
        if node.right:
            self.getDepth(node.right, depth + 1)

 

posted on 2025-09-08 21:29  axuu  阅读(8)  评论(0)    收藏  举报