Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Minimum_Depth_of_Binary_Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
一回目。答えを見た。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

再帰を使った解法も書いてみるとよいかもしれません。

複数の書き方ができるようにしておき、状況に応じて適切な書き方を選んでかけるようになっていると理想的だと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

念のための確認ですが、BFSでもですか?DFSならわかりますが...

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DFS のほうです。


```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)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

list() の pop(0) を呼び出すと、それより後の要素のデータの移動が行われるため、効率的に処理できません。https://github.com/python/cpython/blob/main/Objects/listobject.c#L1511

https://docs.python.org/ja/3/tutorial/datastructures.html#using-lists-as-queues

リストをキュー (queue) として使うことも可能です。この場合、最初に追加した要素を最初に取り出します ("first-in, first-out")。しかし、リストでは効率的にこの目的を達成することが出来ません。追加(append)や取り出し(pop)をリストの末尾に対して行うと速いのですが、挿入(insert)や取り出し(pop)をリストの先頭に対して行うと遅くなってしまいます(他の要素をひとつずつずらす必要があるからです)。

代わりに collections.deque を使うことをお勧めいたします。
https://docs.python.org/ja/3/library/collections.html#collections.deque

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

知りませんでした!ありがとうございます!

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))
```