Conversation
| frontier = deque([root]) | ||
| current_depth = 1 | ||
| while True: | ||
| next_frontier = deque() |
| frontier = deque() | ||
| frontier.append(root) | ||
| while frontier: | ||
| num_cur_frontier = len(frontier) |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)
また、 frontier は一つだけ存在していて、その中に node が複数存在している、と考える人もいると思います。その場合、 num_cur_frontier は不自然に感じられます。
自分なら num_nodes_in_level と名付けると思います。
| while frontier: | ||
| num_cur_frontier = len(frontier) | ||
| depth += 1 | ||
| for _ in range(num_cur_frontier): |
There was a problem hiding this comment.
deque 一つだけを使い、現在のレベルのノードの個数だけループを回すという書き方は、初見の方にとってはもしかしたらわかりづらいかもしれません。最近はこちらの書き方のほうがメジャーなのでしょうか…。
list を 2 つ使って、片方から展開したノードをもう片方に入れるやり方や、 deque の中に要素とレベルの tuple を入れるやり方のほうが良く見かけるかもしれません。
There was a problem hiding this comment.
最近はこちらの書き方のほうがメジャーなのでしょうか…。
自分がそれしか知らなかったので使っていただけですね。最近は提示していただいたリストを二つ使うやり方にしています。
| if root is None: | ||
| return 0 | ||
|
|
||
| def minDepth_helper(node): |
There was a problem hiding this comment.
helper関数を定義する必要はないように思いました。
minDepthの再帰で書けると思います。
手前味噌で恐縮ですが参考にしてください。
https://github.com/tom4649/Coding/blob/111.Minimum-Depth-of-Binary-Tree/111/sol2.py
There was a problem hiding this comment.
これは意図としては最初のroot is Noneは再帰とは別ロジックと捉えて処理を分離したいというのがありました。
このコメントを読んだからですね。
mamo3gr/arai60#20 (comment)
入力がNoneでないことをminDepth()本体で確認してから,引数にNoneでないTreeNodeをとる再帰用のヘルパー関数(12行目以下の内容をそのまま関数化)を用意してそちらにrootを渡す方が,作業の分離という意味でわかりやすいと感じます.
There was a problem hiding this comment.
なるほど、最初の呼び出し以外ではNoneが与えられることはないですね。
勉強になりました。
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/