Skip to content

Create Minimum_Depth_of_Binary_Tree.md#13

Open
tshimosake wants to merge 1 commit intomasterfrom
tshimosake-patch-11
Open

Create Minimum_Depth_of_Binary_Tree.md#13
tshimosake wants to merge 1 commit intomasterfrom
tshimosake-patch-11

Conversation

@tshimosake
Copy link
Owner


queue = [(root, 1)]
while queue:
node, depth = queue.pop(0)
Copy link

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
Owner Author

Choose a reason for hiding this comment

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

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

@@ -0,0 +1,37 @@
一回目。答えを見た。
Copy link

Choose a reason for hiding this comment

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

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

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

Copy link
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

Choose a reason for hiding this comment

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

DFS のほうです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants