Skip to content

104. Maximum Depth of Binary Tree #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

104. Maximum Depth of Binary Tree #21

wants to merge 1 commit into from

Conversation

potrue
Copy link
Owner

@potrue potrue commented May 26, 2025

https://github.com/rossy0213/leetcode/pull/10/files

再帰を使う選択肢は思い浮かばなかった・・・選択肢の一つにはしておきたい。
next_nodesのリストを作っていって次のループに入る前にnodesに代入するやり方とtupleなどで深さも一緒に保存しておくやり方、どっちのが読みやすいですかね?
Copy link

Choose a reason for hiding this comment

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

私はタプルのほうが趣味ですね。どちらでもいいのではないでしょうか。

if node.right is not None:
queue.append((node.right, depth + 1))
return depth
```

Choose a reason for hiding this comment

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

読みやすかったです。Step2で見かけた再帰を使う方法も何も見ずに再現できるかを試してみると勉強になると思いました。

while queue:
node, depth = queue.popleft()
append_if_not_none(node.left, depth + 1)
append_if_not_none(node.right, depth + 1)

Choose a reason for hiding this comment

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

個人的には append_if_exist などもありかなと感じました。

def append_if_not_none(node, depth):
if node is not None:
queue.append((node, depth))
depth = 0

Choose a reason for hiding this comment

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

ここら辺にqueueの初期化があった方が分かりやすいと思いました。今回はヘルパー関数が短いので問題なさそうですが。

Copy link
Owner Author

Choose a reason for hiding this comment

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

上から読んでいったときにヘルパー関数の中でまだ導入されてない変数を操作することになるのでヘルパー変数の前に置く方がいいかなと思ったんですが、変数の定義はあとでも良いという人も多いんですかね? 👀

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.

5 participants