Conversation
|
|
||
| queue = [(root, 1)] | ||
| while queue: | ||
| node, depth = queue.pop(0) |
There was a problem hiding this comment.
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
| @@ -0,0 +1,37 @@ | |||
| 一回目。答えを見た。 | |||
There was a problem hiding this comment.
再帰を使った解法も書いてみるとよいかもしれません。
複数の書き方ができるようにしておき、状況に応じて適切な書き方を選んでかけるようになっていると理想的だと思います。
There was a problem hiding this comment.
念のための確認ですが、BFSでもですか?DFSならわかりますが...
https://leetcode.com/problems/minimum-depth-of-binary-tree/