From d15c54f43fe0df608d207f269e8bb589c5cebd3d Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 00:26:20 -0500 Subject: [PATCH] =?UTF-8?q?Update=200111.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index bda12ff0..0c086f1b 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -359,6 +359,39 @@ class Solution: return depth ``` +迭代法: + +```python +# 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 + + queue = collections.deque([(root, 1)]) + + while queue: + node, depth = queue.popleft() + + # Check if the node is a leaf node + if not node.left and not node.right: + return depth + + # Add left and right child to the queue + if node.left: + queue.append((node.left, depth+1)) + if node.right: + queue.append((node.right, depth+1)) + + return 0 + +``` ## Go