diff --git a/Python3/111. Minimum Depth of Binary Tree.md b/Python3/111. Minimum Depth of Binary Tree.md new file mode 100644 index 0000000..a21f44e --- /dev/null +++ b/Python3/111. Minimum Depth of Binary Tree.md @@ -0,0 +1,79 @@ +## Step 1. Initial Solution + +- 葉が出てきたら終了できるBFSで実装するのが自然に感じた +- rootがNoneの時の返り値は0じゃないといけないらしい + - 初めはValueErrorにしていたが駄目だった + +```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: Optional[TreeNode]) -> int: + if root is None: + return 0 + remaining_nodes_and_depths: List[Tuple[TreeNode, int]] = deque([(root, 1)]) + while remaining_nodes_and_depths: + node, depth = remaining_nodes_and_depths.popleft() + if node.left is None and node.right is None: + return depth + if node.left is not None: + remaining_nodes_and_depths.append((node.left, depth + 1)) + if node.right is not None: + remaining_nodes_and_depths.append((node.right, depth + 1)) + raise ValueError('Invalid nodes') +``` + +### Complexity Analysis + +- 時間計算量:O(n) + - 最悪の場合でも全てのノードを見る前に終わる +- 空間計算量:O(n) + +## Step 2. Alternatives + +- min_depthを定義している人がいたがBFSなら不要という認識なので疑問に思った +- depthをノードごとに保持しない方法もあるが、二重ループになって深くなるので微妙かなと感じた + - ただ、こちらのやり方を好む人も多そう +- 最後にエラー処理を入れているがあまり同じことをしてる人はいなさそうなので不要かもしれない +- 木構造の高さの測り方として行きがけと帰りがけ・上から配ると下から集めるといった表現をしている人がいた + - 高さを知りたいだけなら行きがけで良いのかなと感じた + - あまり帰りがけのメリットが分からなかった + - 再帰で書くと自然なのはこちらになりそう + +```python +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + if root.left is None and root.right is None: + return 1 + if root.left is None: + return 1 + self.minDepth(root.right) + if root.right is None: + return 1 + self.minDepth(root.left) + return 1 + min(self.minDepth(root.right), self.minDepth(root.left)) +``` + +## Step 3. Final Solution + +- 3回のうち1回は二重ループで書いてみたが最後はほぼStep 1と同じなものがしっくりきた + +```python +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + remaining_nodes_and_depths: List[Tuple[TreeNode, int]] = deque([(root, 1)]) + while remaining_nodes_and_depths: + node, depth = remaining_nodes_and_depths.popleft() + if node is None: + continue + if node.left is None and node.right is None: + return depth + remaining_nodes_and_depths.append((node.left, depth + 1)) + remaining_nodes_and_depths.append((node.right, depth + 1)) +```