From eaba8b19a3fe8e421eedd719f116d1510719c2c8 Mon Sep 17 00:00:00 2001 From: tshimosake <102135053+tshimosake@users.noreply.github.com> Date: Sun, 9 Feb 2025 16:15:43 +0900 Subject: [PATCH] Create Minimum_Depth_of_Binary_Tree.md https://leetcode.com/problems/minimum-depth-of-binary-tree/ --- Minimum_Depth_of_Binary_Tree.md | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Minimum_Depth_of_Binary_Tree.md diff --git a/Minimum_Depth_of_Binary_Tree.md b/Minimum_Depth_of_Binary_Tree.md new file mode 100644 index 0000000..4c6f9c9 --- /dev/null +++ b/Minimum_Depth_of_Binary_Tree.md @@ -0,0 +1,37 @@ +一回目。答えを見た。 + +```py +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + + queue = [(root, 1)] + while queue: + node, depth = queue.pop(0) + if node.left is None and node.right is None: + return depth + if node.left: + queue.append((node.left, depth + 1)) + if node.right: + queue.append((node.right, depth + 1)) +``` + +2回目と3回目。子ノードが None かどうかの判定は(1つ目と2, 3個目で)そろえたほうがよいと判断した。 + +```py +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + + queue = [(root, 1)] + while queue: + node, depth = queue.pop(0) + if node.left is None and node.right is None: + return depth + if node.left is not None: + queue.append((node.left, depth + 1)) + if node.right is not None: + queue.append((node.right, depth + 1)) +```