Skip to content

111 minimum depth of binary tree#22

Open
kitano-kazuki wants to merge 5 commits intomainfrom
111-minimum-depth-of-binary-tree
Open

111 minimum depth of binary tree#22
kitano-kazuki wants to merge 5 commits intomainfrom
111-minimum-depth-of-binary-tree

Conversation

@kitano-kazuki
Copy link
Owner

frontier = deque([root])
current_depth = 1
while True:
next_frontier = deque()

Choose a reason for hiding this comment

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

この書き方だったら、dequeではなく、listで良さそうですね。

frontier = deque()
frontier.append(root)
while frontier:
num_cur_frontier = len(frontier)
Copy link

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
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):
Copy link

@nodchip nodchip Mar 17, 2026

Choose a reason for hiding this comment

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

deque 一つだけを使い、現在のレベルのノードの個数だけループを回すという書き方は、初見の方にとってはもしかしたらわかりづらいかもしれません。最近はこちらの書き方のほうがメジャーなのでしょうか…。
list を 2 つ使って、片方から展開したノードをもう片方に入れるやり方や、 deque の中に要素とレベルの tuple を入れるやり方のほうが良く見かけるかもしれません。

Copy link
Owner Author

Choose a reason for hiding this comment

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

最近はこちらの書き方のほうがメジャーなのでしょうか…。

自分がそれしか知らなかったので使っていただけですね。最近は提示していただいたリストを二つ使うやり方にしています。

if root is None:
return 0

def minDepth_helper(node):
Copy link

Choose a reason for hiding this comment

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

helper関数を定義する必要はないように思いました。
minDepthの再帰で書けると思います。
手前味噌で恐縮ですが参考にしてください。
https://github.com/tom4649/Coding/blob/111.Minimum-Depth-of-Binary-Tree/111/sol2.py

Copy link
Owner Author

Choose a reason for hiding this comment

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

これは意図としては最初のroot is Noneは再帰とは別ロジックと捉えて処理を分離したいというのがありました。

このコメントを読んだからですね。
mamo3gr/arai60#20 (comment)

入力がNoneでないことをminDepth()本体で確認してから,引数にNoneでないTreeNodeをとる再帰用のヘルパー関数(12行目以下の内容をそのまま関数化)を用意してそちらにrootを渡す方が,作業の分離という意味でわかりやすいと感じます.

Copy link

Choose a reason for hiding this comment

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

なるほど、最初の呼び出し以外ではNoneが与えられることはないですね。
勉強になりました。

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.

4 participants