leetcode_二叉树 111. 二叉树的最小深度

111. 二叉树的最小深度

  • 给定一个二叉树,找出其最小深度。

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

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

1. 深度遍历DFS(递归)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def minDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        if not root:
            return 0
            # 空数深度为0
        
        def depth(node):
        
			# 如果是叶子节点,返回 1
            if not node.left and not node.right:
                return 1
                
            # 如果只有一个孩子节点,取另一个孩子的深度
            if not node.left:
                return depth(node.right) + 1
            if not node.right:
                return depth(node.left) + 1
                
			# 如果有两个孩子节点,返回左右孩子中的最小深度 + 1
            return min(depth(node.left), depth(node.right)) + 1
        
        return depth(root)
  • 时间复杂度是 O(n),n是节点个数
  • 空间复杂度是 O(h),h是树的高度

2. 广度遍历BFS(栈)

  • BFS用队列来遍历树的每一层。每次遍历到一个节点时,如果它是叶子节点(即没有左子树和右子树),则返回当前的深度。
  • 早期终止:一旦找到第一个叶子节点,就立即返回当前的深度,不再继续遍历其他节点。这样可以避免无谓的递归,优化了时间复杂度。
from collections import deque

class Solution(object):
    def minDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        if not root:
            return 0  # 空树的深度是 0

        # 使用队列进行层序遍历
        queue = deque([(root, 1)])  # 存储节点和当前的深度
        while queue:
            node, depth = queue.popleft()
            
            # 如果是叶子节点,直接返回当前深度
            if not node.left and not node.right:
                return depth
            
            # 如果有左子树,加入队列
            if node.left:
                queue.append((node.left, depth + 1))
            
            # 如果有右子树,加入队列
            if node.right:
                queue.append((node.right, depth + 1))
  • 时间复杂度是 O(n),n是节点个数
  • 空间复杂度是 O(n)

你可能感兴趣的:(leetcode,算法,深度优先)