Conversation
| ``` | ||
|
|
||
| recursive, preorder DFS traversal, | ||
| 2パターン書いてみたが、あまり名前がしっくりこない。 |
| result = [] | ||
| while nodes: | ||
| values_in_this_level = [] | ||
| nodes_in_next_level = [] |
There was a problem hiding this comment.
好みの問題ですが変数名の中に前置詞が入ると変数名が長くなりがちなので、それを避けるためにnext_level_nodesみたいにすることもあります
| return | ||
|
|
||
| nonlocal level_ordered_values | ||
| while not len(level_ordered_values) > level: |
There was a problem hiding this comment.
条件部分にnotがあると読む時に反転させる一手間で若干読みづらくなるので、notをつけると読みやすくなる状況以外はnotをつけないことをおすすめします。
There was a problem hiding this comment.
確かに上から下に読むものと考えたらここの否定は分かりにくいですね。
自分の中では、このループを抜けたつぎの行のlevel_ordered_values[level].append(node.val)で例外を発生させない条件の否定みたいな意味で書いてました。
つまり、ループを抜ければ、level_ordered_values[level].append(node.val)はうまく通るだろうみたいなニュアンスです。
| return | ||
|
|
||
| nonlocal level_ordered_values | ||
| while not len(level_ordered_values) > level: |
There was a problem hiding this comment.
ここwhileである必然性がなさそうで、なぜwhileなんだろうという違和感を感じます。
There was a problem hiding this comment.
https://discord.com/channels/1084280443945353267/1200089668901937312/1211248049884499988
これを参考にしてます。
preorder traversalをしており一段飛ばしになるとかはないので、ifでもいい場所ではあります。
必然性とまで言えるような論拠はないです。
| return level_ordered_values | ||
| while not len(level_ordered_values) > level: | ||
| level_ordered_values.append([]) | ||
| level_ordered_values[level].append(node.val) |
| if node.left is not None: | ||
| nodes_in_next_level.append(node.left) | ||
| if node.right is not None: |
There was a problem hiding this comment.
is not None はなくてもシンプルで良いですが、書いた方が明示的という人もいるかもしれません。
好みでしょうか。
| nodes = [root] | ||
| result = [] | ||
| while True: | ||
| nodes = list(filter(None, nodes)) |
There was a problem hiding this comment.
取り出す前にfilterで除去するというのは、今まで考えたことがありませんでしたが、振る舞いとしては理にかなった操作だと感じました。
| - https://github.com/hayashi-ay/leetcode/pull/32/files | ||
| - DFS preorder recursive traversal、階層別でないdequeを使ったBFS | ||
|
|
||
| 感想:BFS以外の書き方が思いつかなかったが、levelさえトラックしていればDFSでやろうが動作する。 |
There was a problem hiding this comment.
DFSは直感に反する感じがして食わず嫌いしてましたが、解けるんですね。勉強になりました。
それと、深さごとに、入る部屋[]が決まってて、そこに放り込んでいく操作ですが、辞書みたいな使い方で良いですね。
level_ordered_values[level].append(node.val)
| nodes_in_next_level.append(node.right) | ||
| nodes_in_level = nodes_in_next_level | ||
| level_ordered_values.append(values_in_level) | ||
| return level_ordered_values |
https://leetcode.com/problems/binary-tree-level-order-traversal/description/